Add test for CLIENT_EARLY_TRAFFIC_SECRET key logging
[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
20 #include "ssltestlib.h"
21 #include "testutil.h"
22 #include "testutil/output.h"
23 #include "internal/nelem.h"
24 #include "../ssl/ssl_locl.h"
25
26 static char *cert = NULL;
27 static char *privkey = NULL;
28 static char *srpvfile = NULL;
29 static char *tmpfilename = NULL;
30
31 #define LOG_BUFFER_SIZE 2048
32 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
33 static size_t server_log_buffer_index = 0;
34 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
35 static size_t client_log_buffer_index = 0;
36 static int error_writing_log = 0;
37
38 #ifndef OPENSSL_NO_OCSP
39 static const unsigned char orespder[] = "Dummy OCSP Response";
40 static int ocsp_server_called = 0;
41 static int ocsp_client_called = 0;
42
43 static int cdummyarg = 1;
44 static X509 *ocspcert = NULL;
45 #endif
46
47 #define NUM_EXTRA_CERTS 40
48 #define CLIENT_VERSION_LEN      2
49
50 /*
51  * This structure is used to validate that the correct number of log messages
52  * of various types are emitted when emitting secret logs.
53  */
54 struct sslapitest_log_counts {
55     unsigned int rsa_key_exchange_count;
56     unsigned int master_secret_count;
57     unsigned int client_early_secret_count;
58     unsigned int client_handshake_secret_count;
59     unsigned int server_handshake_secret_count;
60     unsigned int client_application_secret_count;
61     unsigned int server_application_secret_count;
62     unsigned int exporter_secret_count;
63 };
64
65
66 static unsigned char serverinfov1[] = {
67     0xff, 0xff, /* Dummy extension type */
68     0x00, 0x01, /* Extension length is 1 byte */
69     0xff        /* Dummy extension data */
70 };
71
72 static unsigned char serverinfov2[] = {
73     0x00, 0x00, 0x00,
74     (unsigned char)(SSL_EXT_CLIENT_HELLO & 0xff), /* Dummy context - 4 bytes */
75     0xff, 0xff, /* Dummy extension type */
76     0x00, 0x01, /* Extension length is 1 byte */
77     0xff        /* Dummy extension data */
78 };
79
80 static void client_keylog_callback(const SSL *ssl, const char *line)
81 {
82     int line_length = strlen(line);
83
84     /* If the log doesn't fit, error out. */
85     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
86         TEST_info("Client log too full");
87         error_writing_log = 1;
88         return;
89     }
90
91     strcat(client_log_buffer, line);
92     client_log_buffer_index += line_length;
93     client_log_buffer[client_log_buffer_index++] = '\n';
94 }
95
96 static void server_keylog_callback(const SSL *ssl, const char *line)
97 {
98     int line_length = strlen(line);
99
100     /* If the log doesn't fit, error out. */
101     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
102         TEST_info("Server log too full");
103         error_writing_log = 1;
104         return;
105     }
106
107     strcat(server_log_buffer, line);
108     server_log_buffer_index += line_length;
109     server_log_buffer[server_log_buffer_index++] = '\n';
110 }
111
112 static int compare_hex_encoded_buffer(const char *hex_encoded,
113                                       size_t hex_length,
114                                       const uint8_t *raw,
115                                       size_t raw_length)
116 {
117     size_t i, j;
118     char hexed[3];
119
120     if (!TEST_size_t_eq(raw_length * 2, hex_length))
121         return 1;
122
123     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
124         sprintf(hexed, "%02x", raw[i]);
125         if (!TEST_int_eq(hexed[0], hex_encoded[j])
126                 || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
127             return 1;
128     }
129
130     return 0;
131 }
132
133 static int test_keylog_output(char *buffer, const SSL *ssl,
134                               const SSL_SESSION *session,
135                               struct sslapitest_log_counts *expected)
136 {
137     char *token = NULL;
138     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0};
139     size_t client_random_size = SSL3_RANDOM_SIZE;
140     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
141     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
142     unsigned int rsa_key_exchange_count = 0;
143     unsigned int master_secret_count = 0;
144     unsigned int client_early_secret_count = 0;
145     unsigned int client_handshake_secret_count = 0;
146     unsigned int server_handshake_secret_count = 0;
147     unsigned int client_application_secret_count = 0;
148     unsigned int server_application_secret_count = 0;
149     unsigned int exporter_secret_count = 0;
150
151     for (token = strtok(buffer, " \n"); token != NULL;
152          token = strtok(NULL, " \n")) {
153         if (strcmp(token, "RSA") == 0) {
154             /*
155              * Premaster secret. Tokens should be: 16 ASCII bytes of
156              * hex-encoded encrypted secret, then the hex-encoded pre-master
157              * secret.
158              */
159             if (!TEST_ptr(token = strtok(NULL, " \n")))
160                 return 0;
161             if (!TEST_size_t_eq(strlen(token), 16))
162                 return 0;
163             if (!TEST_ptr(token = strtok(NULL, " \n")))
164                 return 0;
165             /*
166              * We can't sensibly check the log because the premaster secret is
167              * transient, and OpenSSL doesn't keep hold of it once the master
168              * secret is generated.
169              */
170             rsa_key_exchange_count++;
171         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
172             /*
173              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
174              * client random, then the hex-encoded master secret.
175              */
176             client_random_size = SSL_get_client_random(ssl,
177                                                        actual_client_random,
178                                                        SSL3_RANDOM_SIZE);
179             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
180                 return 0;
181
182             if (!TEST_ptr(token = strtok(NULL, " \n")))
183                 return 0;
184             if (!TEST_size_t_eq(strlen(token), 64))
185                 return 0;
186             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
187                                                        actual_client_random,
188                                                        client_random_size)))
189                 return 0;
190
191             if (!TEST_ptr(token = strtok(NULL, " \n")))
192                 return 0;
193             master_key_size = SSL_SESSION_get_master_key(session,
194                                                          actual_master_key,
195                                                          master_key_size);
196             if (!TEST_size_t_ne(master_key_size, 0))
197                 return 0;
198             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
199                                                        actual_master_key,
200                                                        master_key_size)))
201                 return 0;
202             master_secret_count++;
203         } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0
204                     || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
205                     || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
206                     || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
207                     || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0
208                     || strcmp(token, "EXPORTER_SECRET") == 0) {
209             /*
210              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
211              * client random, and then the hex-encoded secret. In this case,
212              * we treat all of these secrets identically and then just
213              * distinguish between them when counting what we saw.
214              */
215             if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0)
216                 client_early_secret_count++;
217             else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
218                 client_handshake_secret_count++;
219             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
220                 server_handshake_secret_count++;
221             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
222                 client_application_secret_count++;
223             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
224                 server_application_secret_count++;
225             else if (strcmp(token, "EXPORTER_SECRET") == 0)
226                 exporter_secret_count++;
227
228             client_random_size = SSL_get_client_random(ssl,
229                                                        actual_client_random,
230                                                        SSL3_RANDOM_SIZE);
231             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
232                 return 0;
233
234             if (!TEST_ptr(token = strtok(NULL, " \n")))
235                 return 0;
236             if (!TEST_size_t_eq(strlen(token), 64))
237                 return 0;
238             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
239                                                        actual_client_random,
240                                                        client_random_size)))
241                 return 0;
242
243             if (!TEST_ptr(token = strtok(NULL, " \n")))
244                 return 0;
245
246             /*
247              * TODO(TLS1.3): test that application traffic secrets are what
248              * we expect */
249         } else {
250             TEST_info("Unexpected token %s\n", token);
251             return 0;
252         }
253     }
254
255     /* Got what we expected? */
256     if (!TEST_size_t_eq(rsa_key_exchange_count,
257                         expected->rsa_key_exchange_count)
258             || !TEST_size_t_eq(master_secret_count,
259                                expected->master_secret_count)
260             || !TEST_size_t_eq(client_early_secret_count,
261                                expected->client_early_secret_count)
262             || !TEST_size_t_eq(client_handshake_secret_count,
263                                expected->client_handshake_secret_count)
264             || !TEST_size_t_eq(server_handshake_secret_count,
265                                expected->server_handshake_secret_count)
266             || !TEST_size_t_eq(client_application_secret_count,
267                                expected->client_application_secret_count)
268             || !TEST_size_t_eq(server_application_secret_count,
269                                expected->server_application_secret_count)
270             || !TEST_size_t_eq(exporter_secret_count,
271                                expected->exporter_secret_count))
272         return 0;
273     return 1;
274 }
275
276 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
277 static int test_keylog(void)
278 {
279     SSL_CTX *cctx = NULL, *sctx = NULL;
280     SSL *clientssl = NULL, *serverssl = NULL;
281     int testresult = 0;
282     struct sslapitest_log_counts expected = {0};
283
284     /* Clean up logging space */
285     memset(client_log_buffer, 0, sizeof(client_log_buffer));
286     memset(server_log_buffer, 0, sizeof(server_log_buffer));
287     client_log_buffer_index = 0;
288     server_log_buffer_index = 0;
289     error_writing_log = 0;
290
291     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
292                                        TLS_client_method(),
293                                        TLS1_VERSION, TLS_MAX_VERSION,
294                                        &sctx, &cctx, cert, privkey)))
295         return 0;
296
297     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
298     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
299     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
300
301     /* We also want to ensure that we use RSA-based key exchange. */
302     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
303         goto end;
304
305     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
306             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
307         goto end;
308     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
309     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
310                    == client_keylog_callback))
311         goto end;
312     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
313     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
314                    == server_keylog_callback))
315         goto end;
316
317     /* Now do a handshake and check that the logs have been written to. */
318     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
319                                       &clientssl, NULL, NULL))
320             || !TEST_true(create_ssl_connection(serverssl, clientssl,
321                                                 SSL_ERROR_NONE))
322             || !TEST_false(error_writing_log)
323             || !TEST_int_gt(client_log_buffer_index, 0)
324             || !TEST_int_gt(server_log_buffer_index, 0))
325         goto end;
326
327     /*
328      * Now we want to test that our output data was vaguely sensible. We
329      * do that by using strtok and confirming that we have more or less the
330      * data we expect. For both client and server, we expect to see one master
331      * secret. The client should also see a RSA key exchange.
332      */
333     expected.rsa_key_exchange_count = 1;
334     expected.master_secret_count = 1;
335     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
336                                       SSL_get_session(clientssl), &expected)))
337         goto end;
338
339     expected.rsa_key_exchange_count = 0;
340     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
341                                       SSL_get_session(serverssl), &expected)))
342         goto end;
343
344     testresult = 1;
345
346 end:
347     SSL_free(serverssl);
348     SSL_free(clientssl);
349     SSL_CTX_free(sctx);
350     SSL_CTX_free(cctx);
351
352     return testresult;
353 }
354 #endif
355
356 #ifndef OPENSSL_NO_TLS1_3
357 static int test_keylog_no_master_key(void)
358 {
359     SSL_CTX *cctx = NULL, *sctx = NULL;
360     SSL *clientssl = NULL, *serverssl = NULL;
361     SSL_SESSION *sess = NULL;
362     int testresult = 0;
363     struct sslapitest_log_counts expected = {0};
364     unsigned char buf[1];
365     size_t readbytes, written;
366
367     /* Clean up logging space */
368     memset(client_log_buffer, 0, sizeof(client_log_buffer));
369     memset(server_log_buffer, 0, sizeof(server_log_buffer));
370     client_log_buffer_index = 0;
371     server_log_buffer_index = 0;
372     error_writing_log = 0;
373
374     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
375                                        TLS1_VERSION, TLS_MAX_VERSION,
376                                        &sctx, &cctx, cert, privkey))
377         || !TEST_true(SSL_CTX_set_max_early_data(sctx,
378                                                  SSL3_RT_MAX_PLAIN_LENGTH))
379         || !TEST_true(SSL_CTX_set_max_early_data(cctx,
380                                                  SSL3_RT_MAX_PLAIN_LENGTH)))
381         return 0;
382
383     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
384             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
385         goto end;
386
387     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
388     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
389                    == client_keylog_callback))
390         goto end;
391
392     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
393     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
394                    == server_keylog_callback))
395         goto end;
396
397     /* Now do a handshake and check that the logs have been written to. */
398     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
399                                       &clientssl, NULL, NULL))
400             || !TEST_true(create_ssl_connection(serverssl, clientssl,
401                                                 SSL_ERROR_NONE))
402             || !TEST_false(error_writing_log))
403         goto end;
404
405     /*
406      * Now we want to test that our output data was vaguely sensible. For this
407      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
408      * TLSv1.3, but we do expect both client and server to emit keys.
409      */
410     expected.client_handshake_secret_count = 1;
411     expected.server_handshake_secret_count = 1;
412     expected.client_application_secret_count = 1;
413     expected.server_application_secret_count = 1;
414     expected.exporter_secret_count = 1;
415     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
416                                       SSL_get_session(clientssl), &expected))
417             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
418                                              SSL_get_session(serverssl),
419                                              &expected)))
420         goto end;
421
422     /* Terminate old session and resume with early data. */
423     sess = SSL_get1_session(clientssl);
424     SSL_shutdown(clientssl);
425     SSL_shutdown(serverssl);
426     SSL_free(serverssl);
427     SSL_free(clientssl);
428     serverssl = clientssl = NULL;
429
430     /* Reset key log */
431     memset(client_log_buffer, 0, sizeof(client_log_buffer));
432     memset(server_log_buffer, 0, sizeof(server_log_buffer));
433     client_log_buffer_index = 0;
434     server_log_buffer_index = 0;
435
436     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
437                                       &clientssl, NULL, NULL))
438             || !TEST_true(SSL_set_session(clientssl, sess))
439             /* Here writing 0 length early data is enough. */
440             || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
441             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
442                                                 &readbytes),
443                             SSL_READ_EARLY_DATA_ERROR)
444             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
445                             SSL_EARLY_DATA_ACCEPTED)
446             || !TEST_true(create_ssl_connection(serverssl, clientssl,
447                           SSL_ERROR_NONE))
448             || !TEST_true(SSL_session_reused(clientssl)))
449         goto end;
450
451     /* In addition to the previous entries, expect early secrets. */
452     expected.client_early_secret_count = 1;
453     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
454                                       SSL_get_session(clientssl), &expected))
455             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
456                                              SSL_get_session(serverssl),
457                                              &expected)))
458         goto end;
459
460     testresult = 1;
461
462 end:
463     SSL_SESSION_free(sess);
464     SSL_free(serverssl);
465     SSL_free(clientssl);
466     SSL_CTX_free(sctx);
467     SSL_CTX_free(cctx);
468
469     return testresult;
470 }
471 #endif
472
473 #ifndef OPENSSL_NO_TLS1_2
474 static int full_client_hello_callback(SSL *s, int *al, void *arg)
475 {
476     int *ctr = arg;
477     const unsigned char *p;
478     int *exts;
479     /* We only configure two ciphers, but the SCSV is added automatically. */
480 #ifdef OPENSSL_NO_EC
481     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0x00, 0xff};
482 #else
483     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
484                                               0x2c, 0x00, 0xff};
485 #endif
486     const int expected_extensions[] = {
487 #ifndef OPENSSL_NO_EC
488                                        11, 10,
489 #endif
490                                        35, 22, 23, 13};
491     size_t len;
492
493     /* Make sure we can defer processing and get called back. */
494     if ((*ctr)++ == 0)
495         return SSL_CLIENT_HELLO_RETRY;
496
497     len = SSL_client_hello_get0_ciphers(s, &p);
498     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
499             || !TEST_size_t_eq(
500                        SSL_client_hello_get0_compression_methods(s, &p), 1)
501             || !TEST_int_eq(*p, 0))
502         return SSL_CLIENT_HELLO_ERROR;
503     if (!SSL_client_hello_get1_extensions_present(s, &exts, &len))
504         return SSL_CLIENT_HELLO_ERROR;
505     if (len != OSSL_NELEM(expected_extensions) ||
506         memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
507         printf("ClientHello callback expected extensions mismatch\n");
508         OPENSSL_free(exts);
509         return SSL_CLIENT_HELLO_ERROR;
510     }
511     OPENSSL_free(exts);
512     return SSL_CLIENT_HELLO_SUCCESS;
513 }
514
515 static int test_client_hello_cb(void)
516 {
517     SSL_CTX *cctx = NULL, *sctx = NULL;
518     SSL *clientssl = NULL, *serverssl = NULL;
519     int testctr = 0, testresult = 0;
520
521     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
522                                        TLS1_VERSION, TLS_MAX_VERSION,
523                                        &sctx, &cctx, cert, privkey)))
524         goto end;
525     SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr);
526
527     /* The gimpy cipher list we configure can't do TLS 1.3. */
528     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
529
530     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
531                         "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
532             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
533                                              &clientssl, NULL, NULL))
534             || !TEST_false(create_ssl_connection(serverssl, clientssl,
535                         SSL_ERROR_WANT_CLIENT_HELLO_CB))
536                 /*
537                  * Passing a -1 literal is a hack since
538                  * the real value was lost.
539                  * */
540             || !TEST_int_eq(SSL_get_error(serverssl, -1),
541                             SSL_ERROR_WANT_CLIENT_HELLO_CB)
542             || !TEST_true(create_ssl_connection(serverssl, clientssl,
543                                                 SSL_ERROR_NONE)))
544         goto end;
545
546     testresult = 1;
547
548 end:
549     SSL_free(serverssl);
550     SSL_free(clientssl);
551     SSL_CTX_free(sctx);
552     SSL_CTX_free(cctx);
553
554     return testresult;
555 }
556 #endif
557
558 static int execute_test_large_message(const SSL_METHOD *smeth,
559                                       const SSL_METHOD *cmeth,
560                                       int min_version, int max_version,
561                                       int read_ahead)
562 {
563     SSL_CTX *cctx = NULL, *sctx = NULL;
564     SSL *clientssl = NULL, *serverssl = NULL;
565     int testresult = 0;
566     int i;
567     BIO *certbio = NULL;
568     X509 *chaincert = NULL;
569     int certlen;
570
571     if (!TEST_ptr(certbio = BIO_new_file(cert, "r")))
572         goto end;
573     chaincert = PEM_read_bio_X509(certbio, NULL, NULL, NULL);
574     BIO_free(certbio);
575     certbio = NULL;
576     if (!TEST_ptr(chaincert))
577         goto end;
578
579     if (!TEST_true(create_ssl_ctx_pair(smeth, cmeth, min_version, max_version,
580                                        &sctx, &cctx, cert, privkey)))
581         goto end;
582
583     if (read_ahead) {
584         /*
585          * Test that read_ahead works correctly when dealing with large
586          * records
587          */
588         SSL_CTX_set_read_ahead(cctx, 1);
589     }
590
591     /*
592      * We assume the supplied certificate is big enough so that if we add
593      * NUM_EXTRA_CERTS it will make the overall message large enough. The
594      * default buffer size is requested to be 16k, but due to the way BUF_MEM
595      * works, it ends up allocating a little over 21k (16 * 4/3). So, in this
596      * test we need to have a message larger than that.
597      */
598     certlen = i2d_X509(chaincert, NULL);
599     OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
600                    (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
601     for (i = 0; i < NUM_EXTRA_CERTS; i++) {
602         if (!X509_up_ref(chaincert))
603             goto end;
604         if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
605             X509_free(chaincert);
606             goto end;
607         }
608     }
609
610     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
611                                       NULL, NULL))
612             || !TEST_true(create_ssl_connection(serverssl, clientssl,
613                                                 SSL_ERROR_NONE)))
614         goto end;
615
616     /*
617      * Calling SSL_clear() first is not required but this tests that SSL_clear()
618      * doesn't leak (when using enable-crypto-mdebug).
619      */
620     if (!TEST_true(SSL_clear(serverssl)))
621         goto end;
622
623     testresult = 1;
624  end:
625     X509_free(chaincert);
626     SSL_free(serverssl);
627     SSL_free(clientssl);
628     SSL_CTX_free(sctx);
629     SSL_CTX_free(cctx);
630
631     return testresult;
632 }
633
634 static int test_large_message_tls(void)
635 {
636     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
637                                       TLS1_VERSION, TLS_MAX_VERSION,
638                                       0);
639 }
640
641 static int test_large_message_tls_read_ahead(void)
642 {
643     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
644                                       TLS1_VERSION, TLS_MAX_VERSION,
645                                       1);
646 }
647
648 #ifndef OPENSSL_NO_DTLS
649 static int test_large_message_dtls(void)
650 {
651     /*
652      * read_ahead is not relevant to DTLS because DTLS always acts as if
653      * read_ahead is set.
654      */
655     return execute_test_large_message(DTLS_server_method(),
656                                       DTLS_client_method(),
657                                       DTLS1_VERSION, DTLS_MAX_VERSION,
658                                       0);
659 }
660 #endif
661
662 #ifndef OPENSSL_NO_OCSP
663 static int ocsp_server_cb(SSL *s, void *arg)
664 {
665     int *argi = (int *)arg;
666     unsigned char *copy = NULL;
667     STACK_OF(OCSP_RESPID) *ids = NULL;
668     OCSP_RESPID *id = NULL;
669
670     if (*argi == 2) {
671         /* In this test we are expecting exactly 1 OCSP_RESPID */
672         SSL_get_tlsext_status_ids(s, &ids);
673         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
674             return SSL_TLSEXT_ERR_ALERT_FATAL;
675
676         id = sk_OCSP_RESPID_value(ids, 0);
677         if (id == NULL || !OCSP_RESPID_match(id, ocspcert))
678             return SSL_TLSEXT_ERR_ALERT_FATAL;
679     } else if (*argi != 1) {
680         return SSL_TLSEXT_ERR_ALERT_FATAL;
681     }
682
683     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
684         return SSL_TLSEXT_ERR_ALERT_FATAL;
685
686     SSL_set_tlsext_status_ocsp_resp(s, copy, sizeof(orespder));
687     ocsp_server_called = 1;
688     return SSL_TLSEXT_ERR_OK;
689 }
690
691 static int ocsp_client_cb(SSL *s, void *arg)
692 {
693     int *argi = (int *)arg;
694     const unsigned char *respderin;
695     size_t len;
696
697     if (*argi != 1 && *argi != 2)
698         return 0;
699
700     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
701     if (!TEST_mem_eq(orespder, len, respderin, len))
702         return 0;
703
704     ocsp_client_called = 1;
705     return 1;
706 }
707
708 static int test_tlsext_status_type(void)
709 {
710     SSL_CTX *cctx = NULL, *sctx = NULL;
711     SSL *clientssl = NULL, *serverssl = NULL;
712     int testresult = 0;
713     STACK_OF(OCSP_RESPID) *ids = NULL;
714     OCSP_RESPID *id = NULL;
715     BIO *certbio = NULL;
716
717     if (!create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
718                              TLS1_VERSION, TLS_MAX_VERSION,
719                              &sctx, &cctx, cert, privkey))
720         return 0;
721
722     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
723         goto end;
724
725     /* First just do various checks getting and setting tlsext_status_type */
726
727     clientssl = SSL_new(cctx);
728     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
729             || !TEST_true(SSL_set_tlsext_status_type(clientssl,
730                                                       TLSEXT_STATUSTYPE_ocsp))
731             || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
732                             TLSEXT_STATUSTYPE_ocsp))
733         goto end;
734
735     SSL_free(clientssl);
736     clientssl = NULL;
737
738     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
739      || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
740         goto end;
741
742     clientssl = SSL_new(cctx);
743     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
744         goto end;
745     SSL_free(clientssl);
746     clientssl = NULL;
747
748     /*
749      * Now actually do a handshake and check OCSP information is exchanged and
750      * the callbacks get called
751      */
752     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
753     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
754     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
755     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
756     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
757                                       &clientssl, NULL, NULL))
758             || !TEST_true(create_ssl_connection(serverssl, clientssl,
759                                                 SSL_ERROR_NONE))
760             || !TEST_true(ocsp_client_called)
761             || !TEST_true(ocsp_server_called))
762         goto end;
763     SSL_free(serverssl);
764     SSL_free(clientssl);
765     serverssl = NULL;
766     clientssl = NULL;
767
768     /* Try again but this time force the server side callback to fail */
769     ocsp_client_called = 0;
770     ocsp_server_called = 0;
771     cdummyarg = 0;
772     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
773                                       &clientssl, NULL, NULL))
774                 /* This should fail because the callback will fail */
775             || !TEST_false(create_ssl_connection(serverssl, clientssl,
776                                                  SSL_ERROR_NONE))
777             || !TEST_false(ocsp_client_called)
778             || !TEST_false(ocsp_server_called))
779         goto end;
780     SSL_free(serverssl);
781     SSL_free(clientssl);
782     serverssl = NULL;
783     clientssl = NULL;
784
785     /*
786      * This time we'll get the client to send an OCSP_RESPID that it will
787      * accept.
788      */
789     ocsp_client_called = 0;
790     ocsp_server_called = 0;
791     cdummyarg = 2;
792     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
793                                       &clientssl, NULL, NULL)))
794         goto end;
795
796     /*
797      * We'll just use any old cert for this test - it doesn't have to be an OCSP
798      * specific one. We'll use the server cert.
799      */
800     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
801             || !TEST_ptr(id = OCSP_RESPID_new())
802             || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
803             || !TEST_ptr(ocspcert = PEM_read_bio_X509(certbio,
804                                                       NULL, NULL, NULL))
805             || !TEST_true(OCSP_RESPID_set_by_key(id, ocspcert))
806             || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
807         goto end;
808     id = NULL;
809     SSL_set_tlsext_status_ids(clientssl, ids);
810     /* Control has been transferred */
811     ids = NULL;
812
813     BIO_free(certbio);
814     certbio = NULL;
815
816     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
817                                          SSL_ERROR_NONE))
818             || !TEST_true(ocsp_client_called)
819             || !TEST_true(ocsp_server_called))
820         goto end;
821
822     testresult = 1;
823
824  end:
825     SSL_free(serverssl);
826     SSL_free(clientssl);
827     SSL_CTX_free(sctx);
828     SSL_CTX_free(cctx);
829     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
830     OCSP_RESPID_free(id);
831     BIO_free(certbio);
832     X509_free(ocspcert);
833     ocspcert = NULL;
834
835     return testresult;
836 }
837 #endif
838
839 #if !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
840 static int new_called, remove_called, get_called;
841
842 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
843 {
844     new_called++;
845     /*
846      * sess has been up-refed for us, but we don't actually need it so free it
847      * immediately.
848      */
849     SSL_SESSION_free(sess);
850     return 1;
851 }
852
853 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
854 {
855     remove_called++;
856 }
857
858 static SSL_SESSION *get_sess_val = NULL;
859
860 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
861                                    int *copy)
862 {
863     get_called++;
864     *copy = 1;
865     return get_sess_val;
866 }
867
868 static int execute_test_session(int maxprot, int use_int_cache,
869                                 int use_ext_cache)
870 {
871     SSL_CTX *sctx = NULL, *cctx = NULL;
872     SSL *serverssl1 = NULL, *clientssl1 = NULL;
873     SSL *serverssl2 = NULL, *clientssl2 = NULL;
874 # ifndef OPENSSL_NO_TLS1_1
875     SSL *serverssl3 = NULL, *clientssl3 = NULL;
876 # endif
877     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
878     int testresult = 0;
879
880     new_called = remove_called = 0;
881
882     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
883                                        TLS1_VERSION, TLS_MAX_VERSION,
884                                        &sctx, &cctx, cert, privkey)))
885         return 0;
886
887     /*
888      * Only allow the max protocol version so we can force a connection failure
889      * later
890      */
891     SSL_CTX_set_min_proto_version(cctx, maxprot);
892     SSL_CTX_set_max_proto_version(cctx, maxprot);
893
894     /* Set up session cache */
895     if (use_ext_cache) {
896         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
897         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
898     }
899     if (use_int_cache) {
900         /* Also covers instance where both are set */
901         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
902     } else {
903         SSL_CTX_set_session_cache_mode(cctx,
904                                        SSL_SESS_CACHE_CLIENT
905                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
906     }
907
908     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
909                                       NULL, NULL))
910             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
911                                                 SSL_ERROR_NONE))
912             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
913         goto end;
914
915     /* Should fail because it should already be in the cache */
916     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
917         goto end;
918     if (use_ext_cache
919             && (!TEST_int_eq(new_called, 1) || !TEST_int_eq(remove_called, 0)))
920         goto end;
921
922     new_called = remove_called = 0;
923     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
924                                       &clientssl2, NULL, NULL))
925             || !TEST_true(SSL_set_session(clientssl2, sess1))
926             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
927                                                 SSL_ERROR_NONE))
928             || !TEST_true(SSL_session_reused(clientssl2)))
929         goto end;
930
931     if (maxprot == TLS1_3_VERSION) {
932         /*
933          * In TLSv1.3 we should have created a new session even though we have
934          * resumed. The original session should also have been removed.
935          */
936         if (use_ext_cache
937                 && (!TEST_int_eq(new_called, 1)
938                     || !TEST_int_eq(remove_called, 1)))
939             goto end;
940     } else {
941         /*
942          * In TLSv1.2 we expect to have resumed so no sessions added or
943          * removed.
944          */
945         if (use_ext_cache
946                 && (!TEST_int_eq(new_called, 0)
947                     || !TEST_int_eq(remove_called, 0)))
948             goto end;
949     }
950
951     SSL_SESSION_free(sess1);
952     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
953         goto end;
954     shutdown_ssl_connection(serverssl2, clientssl2);
955     serverssl2 = clientssl2 = NULL;
956
957     new_called = remove_called = 0;
958     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
959                                       &clientssl2, NULL, NULL))
960             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
961                                                 SSL_ERROR_NONE)))
962         goto end;
963
964     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
965         goto end;
966
967     if (use_ext_cache
968             && (!TEST_int_eq(new_called, 1) || !TEST_int_eq(remove_called, 0)))
969         goto end;
970
971     new_called = remove_called = 0;
972     /*
973      * This should clear sess2 from the cache because it is a "bad" session.
974      * See SSL_set_session() documentation.
975      */
976     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
977         goto end;
978     if (use_ext_cache
979             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
980         goto end;
981     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
982         goto end;
983
984     if (use_int_cache) {
985         /* Should succeeded because it should not already be in the cache */
986         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
987                 || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
988             goto end;
989     }
990
991     new_called = remove_called = 0;
992     /* This shouldn't be in the cache so should fail */
993     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
994         goto end;
995
996     if (use_ext_cache
997             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
998         goto end;
999
1000 # if !defined(OPENSSL_NO_TLS1_1)
1001     new_called = remove_called = 0;
1002     /* Force a connection failure */
1003     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
1004     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
1005                                       &clientssl3, NULL, NULL))
1006             || !TEST_true(SSL_set_session(clientssl3, sess1))
1007             /* This should fail because of the mismatched protocol versions */
1008             || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
1009                                                  SSL_ERROR_NONE)))
1010         goto end;
1011
1012     /* We should have automatically removed the session from the cache */
1013     if (use_ext_cache
1014             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1015         goto end;
1016
1017     /* Should succeed because it should not already be in the cache */
1018     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
1019         goto end;
1020 # endif
1021
1022     /* Now do some tests for server side caching */
1023     if (use_ext_cache) {
1024         SSL_CTX_sess_set_new_cb(cctx, NULL);
1025         SSL_CTX_sess_set_remove_cb(cctx, NULL);
1026         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
1027         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
1028         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
1029         get_sess_val = NULL;
1030     }
1031
1032     SSL_CTX_set_session_cache_mode(cctx, 0);
1033     /* Internal caching is the default on the server side */
1034     if (!use_int_cache)
1035         SSL_CTX_set_session_cache_mode(sctx,
1036                                        SSL_SESS_CACHE_SERVER
1037                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1038
1039     SSL_free(serverssl1);
1040     SSL_free(clientssl1);
1041     serverssl1 = clientssl1 = NULL;
1042     SSL_free(serverssl2);
1043     SSL_free(clientssl2);
1044     serverssl2 = clientssl2 = NULL;
1045     SSL_SESSION_free(sess1);
1046     sess1 = NULL;
1047     SSL_SESSION_free(sess2);
1048     sess2 = NULL;
1049
1050     SSL_CTX_set_max_proto_version(sctx, maxprot);
1051     SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
1052     new_called = remove_called = get_called = 0;
1053     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
1054                                       NULL, NULL))
1055             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
1056                                                 SSL_ERROR_NONE))
1057             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
1058             || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
1059         goto end;
1060
1061     /* Should fail because it should already be in the cache */
1062     if (use_int_cache && !TEST_false(SSL_CTX_add_session(sctx, sess2)))
1063         goto end;
1064
1065     if (use_ext_cache) {
1066         SSL_SESSION *tmp = sess2;
1067
1068         if (!TEST_int_eq(new_called, 1)
1069                 || !TEST_int_eq(remove_called, 0)
1070                 || !TEST_int_eq(get_called, 0))
1071             goto end;
1072         /*
1073          * Delete the session from the internal cache to force a lookup from
1074          * the external cache. We take a copy first because
1075          * SSL_CTX_remove_session() also marks the session as non-resumable.
1076          */
1077         if (use_int_cache) {
1078             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
1079                     || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
1080                 goto end;
1081             SSL_SESSION_free(sess2);
1082         }
1083         sess2 = tmp;
1084     }
1085
1086     new_called = remove_called = get_called = 0;
1087     get_sess_val = sess2;
1088     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1089                                       &clientssl2, NULL, NULL))
1090             || !TEST_true(SSL_set_session(clientssl2, sess1))
1091             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1092                                                 SSL_ERROR_NONE))
1093             || !TEST_true(SSL_session_reused(clientssl2)))
1094         goto end;
1095
1096     if (use_ext_cache) {
1097         if (!TEST_int_eq(remove_called, 0))
1098             goto end;
1099
1100         if (maxprot == TLS1_3_VERSION) {
1101             /*
1102              * Every time we issue a NewSessionTicket we are creating a new
1103              * session for next time in TLSv1.3
1104              */
1105             if (!TEST_int_eq(new_called, 1)
1106                     || !TEST_int_eq(get_called, 0))
1107                 goto end;
1108         } else {
1109             if (!TEST_int_eq(new_called, 0)
1110                     || !TEST_int_eq(get_called, 1))
1111                 goto end;
1112         }
1113     }
1114
1115     testresult = 1;
1116
1117  end:
1118     SSL_free(serverssl1);
1119     SSL_free(clientssl1);
1120     SSL_free(serverssl2);
1121     SSL_free(clientssl2);
1122 # ifndef OPENSSL_NO_TLS1_1
1123     SSL_free(serverssl3);
1124     SSL_free(clientssl3);
1125 # endif
1126     SSL_SESSION_free(sess1);
1127     SSL_SESSION_free(sess2);
1128     SSL_CTX_free(sctx);
1129     SSL_CTX_free(cctx);
1130
1131     return testresult;
1132 }
1133 #endif /* !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
1134
1135 static int test_session_with_only_int_cache(void)
1136 {
1137 #ifndef OPENSSL_NO_TLS1_3
1138     if (!execute_test_session(TLS1_3_VERSION, 1, 0))
1139         return 0;
1140 #endif
1141
1142 #ifndef OPENSSL_NO_TLS1_2
1143     return execute_test_session(TLS1_2_VERSION, 1, 0);
1144 #else
1145     return 1;
1146 #endif
1147 }
1148
1149 static int test_session_with_only_ext_cache(void)
1150 {
1151 #ifndef OPENSSL_NO_TLS1_3
1152     if (!execute_test_session(TLS1_3_VERSION, 0, 1))
1153         return 0;
1154 #endif
1155
1156 #ifndef OPENSSL_NO_TLS1_2
1157     return execute_test_session(TLS1_2_VERSION, 0, 1);
1158 #else
1159     return 1;
1160 #endif
1161 }
1162
1163 static int test_session_with_both_cache(void)
1164 {
1165 #ifndef OPENSSL_NO_TLS1_3
1166     if (!execute_test_session(TLS1_3_VERSION, 1, 1))
1167         return 0;
1168 #endif
1169
1170 #ifndef OPENSSL_NO_TLS1_2
1171     return execute_test_session(TLS1_2_VERSION, 1, 1);
1172 #else
1173     return 1;
1174 #endif
1175 }
1176
1177 #define USE_NULL            0
1178 #define USE_BIO_1           1
1179 #define USE_BIO_2           2
1180 #define USE_DEFAULT         3
1181
1182 #define CONNTYPE_CONNECTION_SUCCESS  0
1183 #define CONNTYPE_CONNECTION_FAIL     1
1184 #define CONNTYPE_NO_CONNECTION       2
1185
1186 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
1187 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
1188 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
1189 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
1190 #else
1191 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
1192 #endif
1193
1194
1195 #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
1196                                 + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
1197                                 + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
1198
1199 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
1200 {
1201     switch (type) {
1202     case USE_NULL:
1203         *res = NULL;
1204         break;
1205     case USE_BIO_1:
1206         *res = bio1;
1207         break;
1208     case USE_BIO_2:
1209         *res = bio2;
1210         break;
1211     }
1212 }
1213
1214
1215 /*
1216  * Tests calls to SSL_set_bio() under various conditions.
1217  *
1218  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
1219  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
1220  * then do more tests where we create a successful connection first using our
1221  * standard connection setup functions, and then call SSL_set_bio() with
1222  * various combinations of valid BIOs or NULL. We then repeat these tests
1223  * following a failed connection. In this last case we are looking to check that
1224  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
1225  */
1226 static int test_ssl_set_bio(int idx)
1227 {
1228     SSL_CTX *sctx = NULL, *cctx = NULL;
1229     BIO *bio1 = NULL;
1230     BIO *bio2 = NULL;
1231     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
1232     SSL *serverssl = NULL, *clientssl = NULL;
1233     int initrbio, initwbio, newrbio, newwbio, conntype;
1234     int testresult = 0;
1235
1236     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
1237         initrbio = idx % 3;
1238         idx /= 3;
1239         initwbio = idx % 3;
1240         idx /= 3;
1241         newrbio = idx % 3;
1242         idx /= 3;
1243         newwbio = idx % 3;
1244         conntype = CONNTYPE_NO_CONNECTION;
1245     } else {
1246         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
1247         initrbio = initwbio = USE_DEFAULT;
1248         newrbio = idx % 2;
1249         idx /= 2;
1250         newwbio = idx % 2;
1251         idx /= 2;
1252         conntype = idx % 2;
1253     }
1254
1255     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1256                                        TLS1_VERSION, TLS_MAX_VERSION,
1257                                        &sctx, &cctx, cert, privkey)))
1258         goto end;
1259
1260     if (conntype == CONNTYPE_CONNECTION_FAIL) {
1261         /*
1262          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
1263          * because we reduced the number of tests in the definition of
1264          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
1265          * mismatched protocol versions we will force a connection failure.
1266          */
1267         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
1268         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1269     }
1270
1271     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1272                                       NULL, NULL)))
1273         goto end;
1274
1275     if (initrbio == USE_BIO_1
1276             || initwbio == USE_BIO_1
1277             || newrbio == USE_BIO_1
1278             || newwbio == USE_BIO_1) {
1279         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
1280             goto end;
1281     }
1282
1283     if (initrbio == USE_BIO_2
1284             || initwbio == USE_BIO_2
1285             || newrbio == USE_BIO_2
1286             || newwbio == USE_BIO_2) {
1287         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
1288             goto end;
1289     }
1290
1291     if (initrbio != USE_DEFAULT) {
1292         setupbio(&irbio, bio1, bio2, initrbio);
1293         setupbio(&iwbio, bio1, bio2, initwbio);
1294         SSL_set_bio(clientssl, irbio, iwbio);
1295
1296         /*
1297          * We want to maintain our own refs to these BIO, so do an up ref for
1298          * each BIO that will have ownership transferred in the SSL_set_bio()
1299          * call
1300          */
1301         if (irbio != NULL)
1302             BIO_up_ref(irbio);
1303         if (iwbio != NULL && iwbio != irbio)
1304             BIO_up_ref(iwbio);
1305     }
1306
1307     if (conntype != CONNTYPE_NO_CONNECTION
1308             && !TEST_true(create_ssl_connection(serverssl, clientssl,
1309                                                 SSL_ERROR_NONE)
1310                           == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
1311         goto end;
1312
1313     setupbio(&nrbio, bio1, bio2, newrbio);
1314     setupbio(&nwbio, bio1, bio2, newwbio);
1315
1316     /*
1317      * We will (maybe) transfer ownership again so do more up refs.
1318      * SSL_set_bio() has some really complicated ownership rules where BIOs have
1319      * already been set!
1320      */
1321     if (nrbio != NULL
1322             && nrbio != irbio
1323             && (nwbio != iwbio || nrbio != nwbio))
1324         BIO_up_ref(nrbio);
1325     if (nwbio != NULL
1326             && nwbio != nrbio
1327             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
1328         BIO_up_ref(nwbio);
1329
1330     SSL_set_bio(clientssl, nrbio, nwbio);
1331
1332     testresult = 1;
1333
1334  end:
1335     BIO_free(bio1);
1336     BIO_free(bio2);
1337
1338     /*
1339      * This test is checking that the ref counting for SSL_set_bio is correct.
1340      * If we get here and we did too many frees then we will fail in the above
1341      * functions. If we haven't done enough then this will only be detected in
1342      * a crypto-mdebug build
1343      */
1344     SSL_free(serverssl);
1345     SSL_free(clientssl);
1346     SSL_CTX_free(sctx);
1347     SSL_CTX_free(cctx);
1348     return testresult;
1349 }
1350
1351 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
1352
1353 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
1354 {
1355     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
1356     SSL_CTX *ctx;
1357     SSL *ssl = NULL;
1358     int testresult = 0;
1359
1360     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
1361             || !TEST_ptr(ssl = SSL_new(ctx))
1362             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
1363             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
1364         goto end;
1365
1366     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
1367
1368     /*
1369      * If anything goes wrong here then we could leak memory, so this will
1370      * be caught in a crypto-mdebug build
1371      */
1372     BIO_push(sslbio, membio1);
1373
1374     /* Verify changing the rbio/wbio directly does not cause leaks */
1375     if (change_bio != NO_BIO_CHANGE) {
1376         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem())))
1377             goto end;
1378         if (change_bio == CHANGE_RBIO)
1379             SSL_set0_rbio(ssl, membio2);
1380         else
1381             SSL_set0_wbio(ssl, membio2);
1382     }
1383     ssl = NULL;
1384
1385     if (pop_ssl)
1386         BIO_pop(sslbio);
1387     else
1388         BIO_pop(membio1);
1389
1390     testresult = 1;
1391  end:
1392     BIO_free(membio1);
1393     BIO_free(sslbio);
1394     SSL_free(ssl);
1395     SSL_CTX_free(ctx);
1396
1397     return testresult;
1398 }
1399
1400 static int test_ssl_bio_pop_next_bio(void)
1401 {
1402     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
1403 }
1404
1405 static int test_ssl_bio_pop_ssl_bio(void)
1406 {
1407     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
1408 }
1409
1410 static int test_ssl_bio_change_rbio(void)
1411 {
1412     return execute_test_ssl_bio(0, CHANGE_RBIO);
1413 }
1414
1415 static int test_ssl_bio_change_wbio(void)
1416 {
1417     return execute_test_ssl_bio(0, CHANGE_WBIO);
1418 }
1419
1420 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
1421 typedef struct {
1422     /* The list of sig algs */
1423     const int *list;
1424     /* The length of the list */
1425     size_t listlen;
1426     /* A sigalgs list in string format */
1427     const char *liststr;
1428     /* Whether setting the list should succeed */
1429     int valid;
1430     /* Whether creating a connection with the list should succeed */
1431     int connsuccess;
1432 } sigalgs_list;
1433
1434 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
1435 # ifndef OPENSSL_NO_EC
1436 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
1437 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
1438 # endif
1439 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
1440 static const int invalidlist2[] = {NID_sha256, NID_undef};
1441 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
1442 static const int invalidlist4[] = {NID_sha256};
1443 static const sigalgs_list testsigalgs[] = {
1444     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
1445 # ifndef OPENSSL_NO_EC
1446     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
1447     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
1448 # endif
1449     {NULL, 0, "RSA+SHA256", 1, 1},
1450 # ifndef OPENSSL_NO_EC
1451     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
1452     {NULL, 0, "ECDSA+SHA512", 1, 0},
1453 # endif
1454     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
1455     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
1456     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
1457     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
1458     {NULL, 0, "RSA", 0, 0},
1459     {NULL, 0, "SHA256", 0, 0},
1460     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
1461     {NULL, 0, "Invalid", 0, 0}
1462 };
1463
1464 static int test_set_sigalgs(int idx)
1465 {
1466     SSL_CTX *cctx = NULL, *sctx = NULL;
1467     SSL *clientssl = NULL, *serverssl = NULL;
1468     int testresult = 0;
1469     const sigalgs_list *curr;
1470     int testctx;
1471
1472     /* Should never happen */
1473     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
1474         return 0;
1475
1476     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
1477     curr = testctx ? &testsigalgs[idx]
1478                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
1479
1480     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1481                                        TLS1_VERSION, TLS_MAX_VERSION,
1482                                        &sctx, &cctx, cert, privkey)))
1483         return 0;
1484
1485     /*
1486      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
1487      * for TLSv1.2 for now until we add a new API.
1488      */
1489     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1490
1491     if (testctx) {
1492         int ret;
1493
1494         if (curr->list != NULL)
1495             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
1496         else
1497             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
1498
1499         if (!ret) {
1500             if (curr->valid)
1501                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
1502             else
1503                 testresult = 1;
1504             goto end;
1505         }
1506         if (!curr->valid) {
1507             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
1508             goto end;
1509         }
1510     }
1511
1512     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1513                                       &clientssl, NULL, NULL)))
1514         goto end;
1515
1516     if (!testctx) {
1517         int ret;
1518
1519         if (curr->list != NULL)
1520             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
1521         else
1522             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
1523         if (!ret) {
1524             if (curr->valid)
1525                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
1526             else
1527                 testresult = 1;
1528             goto end;
1529         }
1530         if (!curr->valid)
1531             goto end;
1532     }
1533
1534     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
1535                                            SSL_ERROR_NONE),
1536                 curr->connsuccess))
1537         goto end;
1538
1539     testresult = 1;
1540
1541  end:
1542     SSL_free(serverssl);
1543     SSL_free(clientssl);
1544     SSL_CTX_free(sctx);
1545     SSL_CTX_free(cctx);
1546
1547     return testresult;
1548 }
1549 #endif
1550
1551 #ifndef OPENSSL_NO_TLS1_3
1552
1553 static SSL_SESSION *clientpsk = NULL;
1554 static SSL_SESSION *serverpsk = NULL;
1555 static const char *pskid = "Identity";
1556 static const char *srvid;
1557
1558 static int use_session_cb_cnt = 0;
1559 static int find_session_cb_cnt = 0;
1560 static int psk_client_cb_cnt = 0;
1561 static int psk_server_cb_cnt = 0;
1562
1563 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
1564                           size_t *idlen, SSL_SESSION **sess)
1565 {
1566     switch (++use_session_cb_cnt) {
1567     case 1:
1568         /* The first call should always have a NULL md */
1569         if (md != NULL)
1570             return 0;
1571         break;
1572
1573     case 2:
1574         /* The second call should always have an md */
1575         if (md == NULL)
1576             return 0;
1577         break;
1578
1579     default:
1580         /* We should only be called a maximum of twice */
1581         return 0;
1582     }
1583
1584     if (clientpsk != NULL)
1585         SSL_SESSION_up_ref(clientpsk);
1586
1587     *sess = clientpsk;
1588     *id = (const unsigned char *)pskid;
1589     *idlen = strlen(pskid);
1590
1591     return 1;
1592 }
1593
1594 #ifndef OPENSSL_NO_PSK
1595 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
1596                                   unsigned int max_id_len,
1597                                   unsigned char *psk,
1598                                   unsigned int max_psk_len)
1599 {
1600     unsigned int psklen = 0;
1601
1602     psk_client_cb_cnt++;
1603
1604     if (strlen(pskid) + 1 > max_id_len)
1605         return 0;
1606
1607     /* We should only ever be called a maximum of twice per connection */
1608     if (psk_client_cb_cnt > 2)
1609         return 0;
1610
1611     if (clientpsk == NULL)
1612         return 0;
1613
1614     /* We'll reuse the PSK we set up for TLSv1.3 */
1615     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
1616         return 0;
1617     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
1618     strncpy(id, pskid, max_id_len);
1619
1620     return psklen;
1621 }
1622 #endif /* OPENSSL_NO_PSK */
1623
1624 static int find_session_cb(SSL *ssl, const unsigned char *identity,
1625                            size_t identity_len, SSL_SESSION **sess)
1626 {
1627     find_session_cb_cnt++;
1628
1629     /* We should only ever be called a maximum of twice per connection */
1630     if (find_session_cb_cnt > 2)
1631         return 0;
1632
1633     if (serverpsk == NULL)
1634         return 0;
1635
1636     /* Identity should match that set by the client */
1637     if (strlen(srvid) != identity_len
1638             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
1639         /* No PSK found, continue but without a PSK */
1640         *sess = NULL;
1641         return 1;
1642     }
1643
1644     SSL_SESSION_up_ref(serverpsk);
1645     *sess = serverpsk;
1646
1647     return 1;
1648 }
1649
1650 #ifndef OPENSSL_NO_PSK
1651 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
1652                                   unsigned char *psk, unsigned int max_psk_len)
1653 {
1654     unsigned int psklen = 0;
1655
1656     psk_server_cb_cnt++;
1657
1658     /* We should only ever be called a maximum of twice per connection */
1659     if (find_session_cb_cnt > 2)
1660         return 0;
1661
1662     if (serverpsk == NULL)
1663         return 0;
1664
1665     /* Identity should match that set by the client */
1666     if (strcmp(srvid, identity) != 0) {
1667         return 0;
1668     }
1669
1670     /* We'll reuse the PSK we set up for TLSv1.3 */
1671     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
1672         return 0;
1673     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
1674
1675     return psklen;
1676 }
1677 #endif /* OPENSSL_NO_PSK */
1678
1679 #define MSG1    "Hello"
1680 #define MSG2    "World."
1681 #define MSG3    "This"
1682 #define MSG4    "is"
1683 #define MSG5    "a"
1684 #define MSG6    "test"
1685 #define MSG7    "message."
1686
1687 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
1688 #define TLS13_AES_128_GCM_SHA256_BYTES  ((const unsigned char *)"\x13\x01")
1689
1690 /*
1691  * Helper method to setup objects for early data test. Caller frees objects on
1692  * error.
1693  */
1694 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
1695                                 SSL **serverssl, SSL_SESSION **sess, int idx)
1696 {
1697     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1698                                        TLS1_VERSION, TLS_MAX_VERSION,
1699                                        sctx, cctx, cert, privkey))
1700         || !TEST_true(SSL_CTX_set_max_early_data(*sctx,
1701                                                  SSL3_RT_MAX_PLAIN_LENGTH))
1702         || !TEST_true(SSL_CTX_set_max_early_data(*cctx,
1703                                                  SSL3_RT_MAX_PLAIN_LENGTH)))
1704         return 0;
1705
1706     if (idx == 1) {
1707         /* When idx == 1 we repeat the tests with read_ahead set */
1708         SSL_CTX_set_read_ahead(*cctx, 1);
1709         SSL_CTX_set_read_ahead(*sctx, 1);
1710     } else if (idx == 2) {
1711         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
1712         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
1713         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
1714         use_session_cb_cnt = 0;
1715         find_session_cb_cnt = 0;
1716         srvid = pskid;
1717     }
1718
1719     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
1720                                       NULL, NULL)))
1721         return 0;
1722
1723     /*
1724      * For one of the run throughs (doesn't matter which one), we'll try sending
1725      * some SNI data in the initial ClientHello. This will be ignored (because
1726      * there is no SNI cb set up by the server), so it should not impact
1727      * early_data.
1728      */
1729     if (idx == 1
1730             && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
1731         return 0;
1732
1733     if (idx == 2) {
1734         /* Create the PSK */
1735         const SSL_CIPHER *cipher = NULL;
1736         const unsigned char key[] = {
1737             0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
1738             0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
1739             0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
1740             0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
1741             0x2c, 0x2d, 0x2e, 0x2f
1742         };
1743
1744         cipher = SSL_CIPHER_find(*clientssl, TLS13_AES_256_GCM_SHA384_BYTES);
1745         clientpsk = SSL_SESSION_new();
1746         if (!TEST_ptr(clientpsk)
1747                 || !TEST_ptr(cipher)
1748                 || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
1749                                                           sizeof(key)))
1750                 || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
1751                 || !TEST_true(
1752                         SSL_SESSION_set_protocol_version(clientpsk,
1753                                                          TLS1_3_VERSION))
1754                    /*
1755                     * We just choose an arbitrary value for max_early_data which
1756                     * should be big enough for testing purposes.
1757                     */
1758                 || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
1759                                                              0x100))
1760                 || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
1761             SSL_SESSION_free(clientpsk);
1762             clientpsk = NULL;
1763             return 0;
1764         }
1765         serverpsk = clientpsk;
1766
1767         if (sess != NULL)
1768             *sess = clientpsk;
1769         return 1;
1770     }
1771
1772     if (sess == NULL)
1773         return 1;
1774
1775     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
1776                                          SSL_ERROR_NONE)))
1777         return 0;
1778
1779     *sess = SSL_get1_session(*clientssl);
1780     SSL_shutdown(*clientssl);
1781     SSL_shutdown(*serverssl);
1782     SSL_free(*serverssl);
1783     SSL_free(*clientssl);
1784     *serverssl = *clientssl = NULL;
1785
1786     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
1787                                       clientssl, NULL, NULL))
1788             || !TEST_true(SSL_set_session(*clientssl, *sess)))
1789         return 0;
1790
1791     return 1;
1792 }
1793
1794 static int test_early_data_read_write(int idx)
1795 {
1796     SSL_CTX *cctx = NULL, *sctx = NULL;
1797     SSL *clientssl = NULL, *serverssl = NULL;
1798     int testresult = 0;
1799     SSL_SESSION *sess = NULL;
1800     unsigned char buf[20], data[1024];
1801     size_t readbytes, written, eoedlen, rawread, rawwritten;
1802     BIO *rbio;
1803
1804     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1805                                         &serverssl, &sess, idx)))
1806         goto end;
1807
1808     /* Write and read some early data */
1809     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1810                                         &written))
1811             || !TEST_size_t_eq(written, strlen(MSG1))
1812             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
1813                                                 sizeof(buf), &readbytes),
1814                             SSL_READ_EARLY_DATA_SUCCESS)
1815             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
1816             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1817                             SSL_EARLY_DATA_ACCEPTED))
1818         goto end;
1819
1820     /*
1821      * Server should be able to write data, and client should be able to
1822      * read it.
1823      */
1824     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
1825                                         &written))
1826             || !TEST_size_t_eq(written, strlen(MSG2))
1827             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1828             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1829         goto end;
1830
1831     /* Even after reading normal data, client should be able write early data */
1832     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
1833                                         &written))
1834             || !TEST_size_t_eq(written, strlen(MSG3)))
1835         goto end;
1836
1837     /* Server should still be able read early data after writing data */
1838     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1839                                          &readbytes),
1840                      SSL_READ_EARLY_DATA_SUCCESS)
1841             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
1842         goto end;
1843
1844     /* Write more data from server and read it from client */
1845     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
1846                                         &written))
1847             || !TEST_size_t_eq(written, strlen(MSG4))
1848             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1849             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
1850         goto end;
1851
1852     /*
1853      * If client writes normal data it should mean writing early data is no
1854      * longer possible.
1855      */
1856     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
1857             || !TEST_size_t_eq(written, strlen(MSG5))
1858             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1859                             SSL_EARLY_DATA_ACCEPTED))
1860         goto end;
1861
1862     /*
1863      * At this point the client has written EndOfEarlyData, ClientFinished and
1864      * normal (fully protected) data. We are going to cause a delay between the
1865      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
1866      * in the read BIO, and then just put back the EndOfEarlyData message.
1867      */
1868     rbio = SSL_get_rbio(serverssl);
1869     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
1870             || !TEST_size_t_lt(rawread, sizeof(data))
1871             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
1872         goto end;
1873
1874     /* Record length is in the 4th and 5th bytes of the record header */
1875     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
1876     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
1877             || !TEST_size_t_eq(rawwritten, eoedlen))
1878         goto end;
1879
1880     /* Server should be told that there is no more early data */
1881     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1882                                          &readbytes),
1883                      SSL_READ_EARLY_DATA_FINISH)
1884             || !TEST_size_t_eq(readbytes, 0))
1885         goto end;
1886
1887     /*
1888      * Server has not finished init yet, so should still be able to write early
1889      * data.
1890      */
1891     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
1892                                         &written))
1893             || !TEST_size_t_eq(written, strlen(MSG6)))
1894         goto end;
1895
1896     /* Push the ClientFinished and the normal data back into the server rbio */
1897     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
1898                                 &rawwritten))
1899             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
1900         goto end;
1901
1902     /* Server should be able to read normal data */
1903     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1904             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
1905         goto end;
1906
1907     /* Client and server should not be able to write/read early data now */
1908     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
1909                                          &written)))
1910         goto end;
1911     ERR_clear_error();
1912     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1913                                          &readbytes),
1914                      SSL_READ_EARLY_DATA_ERROR))
1915         goto end;
1916     ERR_clear_error();
1917
1918     /* Client should be able to read the data sent by the server */
1919     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1920             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
1921         goto end;
1922
1923     /*
1924      * Make sure we process the NewSessionTicket. This arrives post-handshake.
1925      * We attempt a read which we do not expect to return any data.
1926      */
1927     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)))
1928         goto end;
1929
1930     /* Server should be able to write normal data */
1931     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
1932             || !TEST_size_t_eq(written, strlen(MSG7))
1933             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1934             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
1935         goto end;
1936
1937     /* We keep the PSK session around if using PSK */
1938     if (idx != 2)
1939         SSL_SESSION_free(sess);
1940     sess = SSL_get1_session(clientssl);
1941     use_session_cb_cnt = 0;
1942     find_session_cb_cnt = 0;
1943
1944     SSL_shutdown(clientssl);
1945     SSL_shutdown(serverssl);
1946     SSL_free(serverssl);
1947     SSL_free(clientssl);
1948     serverssl = clientssl = NULL;
1949     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1950                                       &clientssl, NULL, NULL))
1951             || !TEST_true(SSL_set_session(clientssl, sess)))
1952         goto end;
1953
1954     /* Write and read some early data */
1955     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1956                                         &written))
1957             || !TEST_size_t_eq(written, strlen(MSG1))
1958             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1959                                                 &readbytes),
1960                             SSL_READ_EARLY_DATA_SUCCESS)
1961             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
1962         goto end;
1963
1964     if (!TEST_int_gt(SSL_connect(clientssl), 0)
1965             || !TEST_int_gt(SSL_accept(serverssl), 0))
1966         goto end;
1967
1968     /* Client and server should not be able to write/read early data now */
1969     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
1970                                          &written)))
1971         goto end;
1972     ERR_clear_error();
1973     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1974                                          &readbytes),
1975                      SSL_READ_EARLY_DATA_ERROR))
1976         goto end;
1977     ERR_clear_error();
1978
1979     /* Client and server should be able to write/read normal data */
1980     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
1981             || !TEST_size_t_eq(written, strlen(MSG5))
1982             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1983             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
1984         goto end;
1985
1986     testresult = 1;
1987
1988  end:
1989     if (sess != clientpsk)
1990         SSL_SESSION_free(sess);
1991     SSL_SESSION_free(clientpsk);
1992     SSL_SESSION_free(serverpsk);
1993     clientpsk = serverpsk = NULL;
1994     SSL_free(serverssl);
1995     SSL_free(clientssl);
1996     SSL_CTX_free(sctx);
1997     SSL_CTX_free(cctx);
1998     return testresult;
1999 }
2000
2001 static int test_early_data_replay(int idx)
2002 {
2003     SSL_CTX *cctx = NULL, *sctx = NULL;
2004     SSL *clientssl = NULL, *serverssl = NULL;
2005     int testresult = 0;
2006     SSL_SESSION *sess = NULL;
2007
2008     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2009                                         &serverssl, &sess, idx)))
2010         goto end;
2011
2012     /*
2013      * The server is configured to accept early data. Create a connection to
2014      * "use up" the ticket
2015      */
2016     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2017             || !TEST_true(SSL_session_reused(clientssl)))
2018         goto end;
2019
2020     SSL_shutdown(clientssl);
2021     SSL_shutdown(serverssl);
2022     SSL_free(serverssl);
2023     SSL_free(clientssl);
2024     serverssl = clientssl = NULL;
2025
2026     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2027                                       &clientssl, NULL, NULL))
2028             || !TEST_true(SSL_set_session(clientssl, sess))
2029             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2030                           SSL_ERROR_NONE))
2031                /*
2032                 * This time we should not have resumed the session because we
2033                 * already used it once.
2034                 */
2035             || !TEST_false(SSL_session_reused(clientssl)))
2036         goto end;
2037
2038     testresult = 1;
2039
2040  end:
2041     if (sess != clientpsk)
2042         SSL_SESSION_free(sess);
2043     SSL_SESSION_free(clientpsk);
2044     SSL_SESSION_free(serverpsk);
2045     clientpsk = serverpsk = NULL;
2046     SSL_free(serverssl);
2047     SSL_free(clientssl);
2048     SSL_CTX_free(sctx);
2049     SSL_CTX_free(cctx);
2050     return testresult;
2051 }
2052
2053 /*
2054  * Helper function to test that a server attempting to read early data can
2055  * handle a connection from a client where the early data should be skipped.
2056  */
2057 static int early_data_skip_helper(int hrr, int idx)
2058 {
2059     SSL_CTX *cctx = NULL, *sctx = NULL;
2060     SSL *clientssl = NULL, *serverssl = NULL;
2061     int testresult = 0;
2062     SSL_SESSION *sess = NULL;
2063     unsigned char buf[20];
2064     size_t readbytes, written;
2065
2066     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2067                                         &serverssl, &sess, idx)))
2068         goto end;
2069
2070     if (hrr) {
2071         /* Force an HRR to occur */
2072         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2073             goto end;
2074     } else if (idx == 2) {
2075         /*
2076          * We force early_data rejection by ensuring the PSK identity is
2077          * unrecognised
2078          */
2079         srvid = "Dummy Identity";
2080     } else {
2081         /*
2082          * Deliberately corrupt the creation time. We take 20 seconds off the
2083          * time. It could be any value as long as it is not within tolerance.
2084          * This should mean the ticket is rejected.
2085          */
2086         if (!TEST_true(SSL_SESSION_set_time(sess, (long)(time(NULL) - 20))))
2087             goto end;
2088     }
2089
2090     /* Write some early data */
2091     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2092                                         &written))
2093             || !TEST_size_t_eq(written, strlen(MSG1)))
2094         goto end;
2095
2096     /* Server should reject the early data and skip over it */
2097     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2098                                          &readbytes),
2099                      SSL_READ_EARLY_DATA_FINISH)
2100             || !TEST_size_t_eq(readbytes, 0)
2101             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2102                             SSL_EARLY_DATA_REJECTED))
2103         goto end;
2104
2105     if (hrr) {
2106         /*
2107          * Finish off the handshake. We perform the same writes and reads as
2108          * further down but we expect them to fail due to the incomplete
2109          * handshake.
2110          */
2111         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2112                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
2113                                &readbytes)))
2114             goto end;
2115     }
2116
2117     /* Should be able to send normal data despite rejection of early data */
2118     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2119             || !TEST_size_t_eq(written, strlen(MSG2))
2120             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2121                             SSL_EARLY_DATA_REJECTED)
2122             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2123             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2124         goto end;
2125
2126     testresult = 1;
2127
2128  end:
2129     if (sess != clientpsk)
2130         SSL_SESSION_free(clientpsk);
2131     SSL_SESSION_free(serverpsk);
2132     clientpsk = serverpsk = NULL;
2133     SSL_SESSION_free(sess);
2134     SSL_free(serverssl);
2135     SSL_free(clientssl);
2136     SSL_CTX_free(sctx);
2137     SSL_CTX_free(cctx);
2138     return testresult;
2139 }
2140
2141 /*
2142  * Test that a server attempting to read early data can handle a connection
2143  * from a client where the early data is not acceptable.
2144  */
2145 static int test_early_data_skip(int idx)
2146 {
2147     return early_data_skip_helper(0, idx);
2148 }
2149
2150 /*
2151  * Test that a server attempting to read early data can handle a connection
2152  * from a client where an HRR occurs.
2153  */
2154 static int test_early_data_skip_hrr(int idx)
2155 {
2156     return early_data_skip_helper(1, idx);
2157 }
2158
2159 /*
2160  * Test that a server attempting to read early data can handle a connection
2161  * from a client that doesn't send any.
2162  */
2163 static int test_early_data_not_sent(int idx)
2164 {
2165     SSL_CTX *cctx = NULL, *sctx = NULL;
2166     SSL *clientssl = NULL, *serverssl = NULL;
2167     int testresult = 0;
2168     SSL_SESSION *sess = NULL;
2169     unsigned char buf[20];
2170     size_t readbytes, written;
2171
2172     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2173                                         &serverssl, &sess, idx)))
2174         goto end;
2175
2176     /* Write some data - should block due to handshake with server */
2177     SSL_set_connect_state(clientssl);
2178     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
2179         goto end;
2180
2181     /* Server should detect that early data has not been sent */
2182     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2183                                          &readbytes),
2184                      SSL_READ_EARLY_DATA_FINISH)
2185             || !TEST_size_t_eq(readbytes, 0)
2186             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2187                             SSL_EARLY_DATA_NOT_SENT)
2188             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2189                             SSL_EARLY_DATA_NOT_SENT))
2190         goto end;
2191
2192     /* Continue writing the message we started earlier */
2193     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2194             || !TEST_size_t_eq(written, strlen(MSG1))
2195             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2196             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
2197             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
2198             || !TEST_size_t_eq(written, strlen(MSG2)))
2199         goto end;
2200
2201     /*
2202      * Should block due to the NewSessionTicket arrival unless we're using
2203      * read_ahead
2204      */
2205     if (idx != 1) {
2206         if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)))
2207             goto end;
2208     }
2209
2210     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2211             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2212         goto end;
2213
2214     testresult = 1;
2215
2216  end:
2217     /* If using PSK then clientpsk and sess are the same */
2218     SSL_SESSION_free(sess);
2219     SSL_SESSION_free(serverpsk);
2220     clientpsk = serverpsk = NULL;
2221     SSL_free(serverssl);
2222     SSL_free(clientssl);
2223     SSL_CTX_free(sctx);
2224     SSL_CTX_free(cctx);
2225     return testresult;
2226 }
2227
2228 static int hostname_cb(SSL *s, int *al, void *arg)
2229 {
2230     const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2231
2232     if (hostname != NULL && strcmp(hostname, "goodhost") == 0)
2233         return  SSL_TLSEXT_ERR_OK;
2234
2235     return SSL_TLSEXT_ERR_NOACK;
2236 }
2237
2238 static const char *servalpn;
2239
2240 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
2241                           unsigned char *outlen, const unsigned char *in,
2242                           unsigned int inlen, void *arg)
2243 {
2244     unsigned int protlen = 0;
2245     const unsigned char *prot;
2246
2247     for (prot = in; prot < in + inlen; prot += protlen) {
2248         protlen = *prot++;
2249         if (in + inlen < prot + protlen)
2250             return SSL_TLSEXT_ERR_NOACK;
2251
2252         if (protlen == strlen(servalpn)
2253                 && memcmp(prot, servalpn, protlen) == 0) {
2254             *out = prot;
2255             *outlen = protlen;
2256             return SSL_TLSEXT_ERR_OK;
2257         }
2258     }
2259
2260     return SSL_TLSEXT_ERR_NOACK;
2261 }
2262
2263 /* Test that a PSK can be used to send early_data */
2264 static int test_early_data_psk(int idx)
2265 {
2266     SSL_CTX *cctx = NULL, *sctx = NULL;
2267     SSL *clientssl = NULL, *serverssl = NULL;
2268     int testresult = 0;
2269     SSL_SESSION *sess = NULL;
2270     unsigned char alpnlist[] = {
2271         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
2272         'l', 'p', 'n'
2273     };
2274 #define GOODALPNLEN     9
2275 #define BADALPNLEN      8
2276 #define GOODALPN        (alpnlist)
2277 #define BADALPN         (alpnlist + GOODALPNLEN)
2278     int err = 0;
2279     unsigned char buf[20];
2280     size_t readbytes, written;
2281     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
2282     int edstatus = SSL_EARLY_DATA_ACCEPTED;
2283
2284     /* We always set this up with a final parameter of "2" for PSK */
2285     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2286                                         &serverssl, &sess, 2)))
2287         goto end;
2288
2289     servalpn = "goodalpn";
2290
2291     /*
2292      * Note: There is no test for inconsistent SNI with late client detection.
2293      * This is because servers do not acknowledge SNI even if they are using
2294      * it in a resumption handshake - so it is not actually possible for a
2295      * client to detect a problem.
2296      */
2297     switch (idx) {
2298     case 0:
2299         /* Set inconsistent SNI (early client detection) */
2300         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
2301         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2302                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
2303             goto end;
2304         break;
2305
2306     case 1:
2307         /* Set inconsistent ALPN (early client detection) */
2308         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
2309         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
2310         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
2311                                                       GOODALPNLEN))
2312                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
2313                                                    BADALPNLEN)))
2314             goto end;
2315         break;
2316
2317     case 2:
2318         /*
2319          * Set invalid protocol version. Technically this affects PSKs without
2320          * early_data too, but we test it here because it is similar to the
2321          * SNI/ALPN consistency tests.
2322          */
2323         err = SSL_R_BAD_PSK;
2324         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
2325             goto end;
2326         break;
2327
2328     case 3:
2329         /*
2330          * Set inconsistent SNI (server detected). In this case the connection
2331          * will succeed but reject early_data.
2332          */
2333         SSL_SESSION_free(serverpsk);
2334         serverpsk = SSL_SESSION_dup(clientpsk);
2335         if (!TEST_ptr(serverpsk)
2336                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
2337             goto end;
2338         edstatus = SSL_EARLY_DATA_REJECTED;
2339         readearlyres = SSL_READ_EARLY_DATA_FINISH;
2340         /* Fall through */
2341     case 4:
2342         /* Set consistent SNI */
2343         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2344                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
2345                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
2346                                 hostname_cb)))
2347             goto end;
2348         break;
2349
2350     case 5:
2351         /*
2352          * Set inconsistent ALPN (server detected). In this case the connection
2353          * will succeed but reject early_data.
2354          */
2355         servalpn = "badalpn";
2356         edstatus = SSL_EARLY_DATA_REJECTED;
2357         readearlyres = SSL_READ_EARLY_DATA_FINISH;
2358         /* Fall through */
2359     case 6:
2360         /*
2361          * Set consistent ALPN.
2362          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
2363          * accepts a list of protos (each one length prefixed).
2364          * SSL_set1_alpn_selected accepts a single protocol (not length
2365          * prefixed)
2366          */
2367         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
2368                                                       GOODALPNLEN - 1))
2369                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
2370                                                    GOODALPNLEN)))
2371             goto end;
2372
2373         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
2374         break;
2375
2376     case 7:
2377         /* Set inconsistent ALPN (late client detection) */
2378         SSL_SESSION_free(serverpsk);
2379         serverpsk = SSL_SESSION_dup(clientpsk);
2380         if (!TEST_ptr(serverpsk)
2381                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
2382                                                              BADALPN + 1,
2383                                                              BADALPNLEN - 1))
2384                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
2385                                                              GOODALPN + 1,
2386                                                              GOODALPNLEN - 1))
2387                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
2388                                                    sizeof(alpnlist))))
2389             goto end;
2390         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
2391         edstatus = SSL_EARLY_DATA_ACCEPTED;
2392         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
2393         /* SSL_connect() call should fail */
2394         connectres = -1;
2395         break;
2396
2397     default:
2398         TEST_error("Bad test index");
2399         goto end;
2400     }
2401
2402     SSL_set_connect_state(clientssl);
2403     if (err != 0) {
2404         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2405                                             &written))
2406                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
2407                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
2408             goto end;
2409     } else {
2410         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2411                                             &written)))
2412             goto end;
2413
2414         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2415                                              &readbytes), readearlyres)
2416                 || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
2417                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
2418                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
2419                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
2420             goto end;
2421     }
2422
2423     testresult = 1;
2424
2425  end:
2426     SSL_SESSION_free(clientpsk);
2427     SSL_SESSION_free(serverpsk);
2428     clientpsk = serverpsk = NULL;
2429     SSL_free(serverssl);
2430     SSL_free(clientssl);
2431     SSL_CTX_free(sctx);
2432     SSL_CTX_free(cctx);
2433     return testresult;
2434 }
2435
2436 /*
2437  * Test that a server that doesn't try to read early data can handle a
2438  * client sending some.
2439  */
2440 static int test_early_data_not_expected(int idx)
2441 {
2442     SSL_CTX *cctx = NULL, *sctx = NULL;
2443     SSL *clientssl = NULL, *serverssl = NULL;
2444     int testresult = 0;
2445     SSL_SESSION *sess = NULL;
2446     unsigned char buf[20];
2447     size_t readbytes, written;
2448
2449     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2450                                         &serverssl, &sess, idx)))
2451         goto end;
2452
2453     /* Write some early data */
2454     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2455                                         &written)))
2456         goto end;
2457
2458     /*
2459      * Server should skip over early data and then block waiting for client to
2460      * continue handshake
2461      */
2462     if (!TEST_int_le(SSL_accept(serverssl), 0)
2463      || !TEST_int_gt(SSL_connect(clientssl), 0)
2464      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2465                      SSL_EARLY_DATA_REJECTED)
2466      || !TEST_int_gt(SSL_accept(serverssl), 0)
2467      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2468                      SSL_EARLY_DATA_REJECTED))
2469         goto end;
2470
2471     /* Send some normal data from client to server */
2472     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2473             || !TEST_size_t_eq(written, strlen(MSG2)))
2474         goto end;
2475
2476     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2477             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2478         goto end;
2479
2480     testresult = 1;
2481
2482  end:
2483     /* If using PSK then clientpsk and sess are the same */
2484     SSL_SESSION_free(sess);
2485     SSL_SESSION_free(serverpsk);
2486     clientpsk = serverpsk = NULL;
2487     SSL_free(serverssl);
2488     SSL_free(clientssl);
2489     SSL_CTX_free(sctx);
2490     SSL_CTX_free(cctx);
2491     return testresult;
2492 }
2493
2494
2495 # ifndef OPENSSL_NO_TLS1_2
2496 /*
2497  * Test that a server attempting to read early data can handle a connection
2498  * from a TLSv1.2 client.
2499  */
2500 static int test_early_data_tls1_2(int idx)
2501 {
2502     SSL_CTX *cctx = NULL, *sctx = NULL;
2503     SSL *clientssl = NULL, *serverssl = NULL;
2504     int testresult = 0;
2505     unsigned char buf[20];
2506     size_t readbytes, written;
2507
2508     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2509                                         &serverssl, NULL, idx)))
2510         goto end;
2511
2512     /* Write some data - should block due to handshake with server */
2513     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
2514     SSL_set_connect_state(clientssl);
2515     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
2516         goto end;
2517
2518     /*
2519      * Server should do TLSv1.2 handshake. First it will block waiting for more
2520      * messages from client after ServerDone. Then SSL_read_early_data should
2521      * finish and detect that early data has not been sent
2522      */
2523     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2524                                          &readbytes),
2525                      SSL_READ_EARLY_DATA_ERROR))
2526         goto end;
2527
2528     /*
2529      * Continue writing the message we started earlier. Will still block waiting
2530      * for the CCS/Finished from server
2531      */
2532     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2533             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2534                                                 &readbytes),
2535                             SSL_READ_EARLY_DATA_FINISH)
2536             || !TEST_size_t_eq(readbytes, 0)
2537             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2538                             SSL_EARLY_DATA_NOT_SENT))
2539         goto end;
2540
2541     /* Continue writing the message we started earlier */
2542     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2543             || !TEST_size_t_eq(written, strlen(MSG1))
2544             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2545                             SSL_EARLY_DATA_NOT_SENT)
2546             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2547             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
2548             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
2549             || !TEST_size_t_eq(written, strlen(MSG2))
2550             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
2551             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2552         goto end;
2553
2554     testresult = 1;
2555
2556  end:
2557     /* If using PSK then clientpsk and sess are the same */
2558     SSL_SESSION_free(clientpsk);
2559     SSL_SESSION_free(serverpsk);
2560     clientpsk = serverpsk = NULL;
2561     SSL_free(serverssl);
2562     SSL_free(clientssl);
2563     SSL_CTX_free(sctx);
2564     SSL_CTX_free(cctx);
2565
2566     return testresult;
2567 }
2568 # endif /* OPENSSL_NO_TLS1_2 */
2569
2570 /*
2571  * Test configuring the TLSv1.3 ciphersuites
2572  *
2573  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
2574  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
2575  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
2576  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
2577  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
2578  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
2579  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
2580  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
2581  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
2582  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
2583  */
2584 static int test_set_ciphersuite(int idx)
2585 {
2586     SSL_CTX *cctx = NULL, *sctx = NULL;
2587     SSL *clientssl = NULL, *serverssl = NULL;
2588     int testresult = 0;
2589
2590     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2591                                        TLS1_VERSION, TLS_MAX_VERSION,
2592                                        &sctx, &cctx, cert, privkey))
2593             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
2594                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
2595         goto end;
2596
2597     if (idx >=4 && idx <= 7) {
2598         /* SSL_CTX explicit cipher list */
2599         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
2600             goto end;
2601     }
2602
2603     if (idx == 0 || idx == 4) {
2604         /* Default ciphersuite */
2605         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2606                                                 "TLS_AES_128_GCM_SHA256")))
2607             goto end;
2608     } else if (idx == 1 || idx == 5) {
2609         /* Non default ciphersuite */
2610         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2611                                                 "TLS_AES_128_CCM_SHA256")))
2612             goto end;
2613     }
2614
2615     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2616                                           &clientssl, NULL, NULL)))
2617         goto end;
2618
2619     if (idx == 8 || idx == 9) {
2620         /* SSL explicit cipher list */
2621         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
2622             goto end;
2623     }
2624
2625     if (idx == 2 || idx == 6 || idx == 8) {
2626         /* Default ciphersuite */
2627         if (!TEST_true(SSL_set_ciphersuites(clientssl,
2628                                             "TLS_AES_128_GCM_SHA256")))
2629             goto end;
2630     } else if (idx == 3 || idx == 7 || idx == 9) {
2631         /* Non default ciphersuite */
2632         if (!TEST_true(SSL_set_ciphersuites(clientssl,
2633                                             "TLS_AES_128_CCM_SHA256")))
2634             goto end;
2635     }
2636
2637     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
2638         goto end;
2639
2640     testresult = 1;
2641
2642  end:
2643     SSL_free(serverssl);
2644     SSL_free(clientssl);
2645     SSL_CTX_free(sctx);
2646     SSL_CTX_free(cctx);
2647
2648     return testresult;
2649 }
2650
2651 static int test_ciphersuite_change(void)
2652 {
2653     SSL_CTX *cctx = NULL, *sctx = NULL;
2654     SSL *clientssl = NULL, *serverssl = NULL;
2655     SSL_SESSION *clntsess = NULL;
2656     int testresult = 0;
2657     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
2658
2659     /* Create a session based on SHA-256 */
2660     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2661                                        TLS1_VERSION, TLS_MAX_VERSION,
2662                                        &sctx, &cctx, cert, privkey))
2663             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
2664                                                    "TLS_AES_128_GCM_SHA256"))
2665             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2666                                           &clientssl, NULL, NULL))
2667             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2668                                                 SSL_ERROR_NONE)))
2669         goto end;
2670
2671     clntsess = SSL_get1_session(clientssl);
2672     /* Save for later */
2673     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
2674     SSL_shutdown(clientssl);
2675     SSL_shutdown(serverssl);
2676     SSL_free(serverssl);
2677     SSL_free(clientssl);
2678     serverssl = clientssl = NULL;
2679
2680 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
2681     /* Check we can resume a session with a different SHA-256 ciphersuite */
2682     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2683                                             "TLS_CHACHA20_POLY1305_SHA256"))
2684             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2685                                              NULL, NULL))
2686             || !TEST_true(SSL_set_session(clientssl, clntsess))
2687             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2688                                                 SSL_ERROR_NONE))
2689             || !TEST_true(SSL_session_reused(clientssl)))
2690         goto end;
2691
2692     SSL_SESSION_free(clntsess);
2693     clntsess = SSL_get1_session(clientssl);
2694     SSL_shutdown(clientssl);
2695     SSL_shutdown(serverssl);
2696     SSL_free(serverssl);
2697     SSL_free(clientssl);
2698     serverssl = clientssl = NULL;
2699 # endif
2700
2701     /*
2702      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
2703      * succeeds but does not resume.
2704      */
2705     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
2706             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2707                                              NULL, NULL))
2708             || !TEST_true(SSL_set_session(clientssl, clntsess))
2709             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2710                                                 SSL_ERROR_SSL))
2711             || !TEST_false(SSL_session_reused(clientssl)))
2712         goto end;
2713
2714     SSL_SESSION_free(clntsess);
2715     clntsess = NULL;
2716     SSL_shutdown(clientssl);
2717     SSL_shutdown(serverssl);
2718     SSL_free(serverssl);
2719     SSL_free(clientssl);
2720     serverssl = clientssl = NULL;
2721
2722     /* Create a session based on SHA384 */
2723     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
2724             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2725                                           &clientssl, NULL, NULL))
2726             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2727                                                 SSL_ERROR_NONE)))
2728         goto end;
2729
2730     clntsess = SSL_get1_session(clientssl);
2731     SSL_shutdown(clientssl);
2732     SSL_shutdown(serverssl);
2733     SSL_free(serverssl);
2734     SSL_free(clientssl);
2735     serverssl = clientssl = NULL;
2736
2737     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2738                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
2739             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
2740                                                    "TLS_AES_256_GCM_SHA384"))
2741             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2742                                              NULL, NULL))
2743             || !TEST_true(SSL_set_session(clientssl, clntsess))
2744                /*
2745                 * We use SSL_ERROR_WANT_READ below so that we can pause the
2746                 * connection after the initial ClientHello has been sent to
2747                 * enable us to make some session changes.
2748                 */
2749             || !TEST_false(create_ssl_connection(serverssl, clientssl,
2750                                                 SSL_ERROR_WANT_READ)))
2751         goto end;
2752
2753     /* Trick the client into thinking this session is for a different digest */
2754     clntsess->cipher = aes_128_gcm_sha256;
2755     clntsess->cipher_id = clntsess->cipher->id;
2756
2757     /*
2758      * Continue the previously started connection. Server has selected a SHA-384
2759      * ciphersuite, but client thinks the session is for SHA-256, so it should
2760      * bail out.
2761      */
2762     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
2763                                                 SSL_ERROR_SSL))
2764             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
2765                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
2766         goto end;
2767
2768     testresult = 1;
2769
2770  end:
2771     SSL_SESSION_free(clntsess);
2772     SSL_free(serverssl);
2773     SSL_free(clientssl);
2774     SSL_CTX_free(sctx);
2775     SSL_CTX_free(cctx);
2776
2777     return testresult;
2778 }
2779
2780 static int test_tls13_psk(int idx)
2781 {
2782     SSL_CTX *sctx = NULL, *cctx = NULL;
2783     SSL *serverssl = NULL, *clientssl = NULL;
2784     const SSL_CIPHER *cipher = NULL;
2785     const unsigned char key[] = {
2786         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
2787         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
2788         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
2789         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
2790     };
2791     int testresult = 0;
2792
2793     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2794                                        TLS1_VERSION, TLS_MAX_VERSION,
2795                                        &sctx, &cctx, cert, privkey)))
2796         goto end;
2797
2798     /*
2799      * We use a ciphersuite with SHA256 to ease testing old style PSK callbacks
2800      * which will always default to SHA256
2801      */
2802     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256")))
2803         goto end;
2804
2805     /*
2806      * Test 0: New style callbacks only
2807      * Test 1: New and old style callbacks (only the new ones should be used)
2808      * Test 2: Old style callbacks only
2809      */
2810     if (idx == 0 || idx == 1) {
2811         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2812         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2813     }
2814 #ifndef OPENSSL_NO_PSK
2815     if (idx == 1 || idx == 2) {
2816         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
2817         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
2818     }
2819 #endif
2820     srvid = pskid;
2821     use_session_cb_cnt = 0;
2822     find_session_cb_cnt = 0;
2823     psk_client_cb_cnt = 0;
2824     psk_server_cb_cnt = 0;
2825
2826     /* Check we can create a connection if callback decides not to send a PSK */
2827     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2828                                              NULL, NULL))
2829             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2830                                                 SSL_ERROR_NONE))
2831             || !TEST_false(SSL_session_reused(clientssl))
2832             || !TEST_false(SSL_session_reused(serverssl)))
2833         goto end;
2834
2835     if (idx == 0 || idx == 1) {
2836         if (!TEST_true(use_session_cb_cnt == 1)
2837                 || !TEST_true(find_session_cb_cnt == 0)
2838                    /*
2839                     * If no old style callback then below should be 0
2840                     * otherwise 1
2841                     */
2842                 || !TEST_true(psk_client_cb_cnt == idx)
2843                 || !TEST_true(psk_server_cb_cnt == 0))
2844             goto end;
2845     } else {
2846         if (!TEST_true(use_session_cb_cnt == 0)
2847                 || !TEST_true(find_session_cb_cnt == 0)
2848                 || !TEST_true(psk_client_cb_cnt == 1)
2849                 || !TEST_true(psk_server_cb_cnt == 0))
2850             goto end;
2851     }
2852
2853     shutdown_ssl_connection(serverssl, clientssl);
2854     serverssl = clientssl = NULL;
2855     use_session_cb_cnt = psk_client_cb_cnt = 0;
2856
2857     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2858                                              NULL, NULL)))
2859         goto end;
2860
2861     /* Create the PSK */
2862     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
2863     clientpsk = SSL_SESSION_new();
2864     if (!TEST_ptr(clientpsk)
2865             || !TEST_ptr(cipher)
2866             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
2867                                                       sizeof(key)))
2868             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
2869             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
2870                                                            TLS1_3_VERSION))
2871             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
2872         goto end;
2873     serverpsk = clientpsk;
2874
2875     /* Check we can create a connection and the PSK is used */
2876     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2877             || !TEST_true(SSL_session_reused(clientssl))
2878             || !TEST_true(SSL_session_reused(serverssl)))
2879         goto end;
2880
2881     if (idx == 0 || idx == 1) {
2882         if (!TEST_true(use_session_cb_cnt == 1)
2883                 || !TEST_true(find_session_cb_cnt == 1)
2884                 || !TEST_true(psk_client_cb_cnt == 0)
2885                 || !TEST_true(psk_server_cb_cnt == 0))
2886             goto end;
2887     } else {
2888         if (!TEST_true(use_session_cb_cnt == 0)
2889                 || !TEST_true(find_session_cb_cnt == 0)
2890                 || !TEST_true(psk_client_cb_cnt == 1)
2891                 || !TEST_true(psk_server_cb_cnt == 1))
2892             goto end;
2893     }
2894
2895     shutdown_ssl_connection(serverssl, clientssl);
2896     serverssl = clientssl = NULL;
2897     use_session_cb_cnt = find_session_cb_cnt = 0;
2898     psk_client_cb_cnt = psk_server_cb_cnt = 0;
2899
2900     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2901                                              NULL, NULL)))
2902         goto end;
2903
2904     /* Force an HRR */
2905     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2906         goto end;
2907
2908     /*
2909      * Check we can create a connection, the PSK is used and the callbacks are
2910      * called twice.
2911      */
2912     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2913             || !TEST_true(SSL_session_reused(clientssl))
2914             || !TEST_true(SSL_session_reused(serverssl)))
2915         goto end;
2916
2917     if (idx == 0 || idx == 1) {
2918         if (!TEST_true(use_session_cb_cnt == 2)
2919                 || !TEST_true(find_session_cb_cnt == 2)
2920                 || !TEST_true(psk_client_cb_cnt == 0)
2921                 || !TEST_true(psk_server_cb_cnt == 0))
2922             goto end;
2923     } else {
2924         if (!TEST_true(use_session_cb_cnt == 0)
2925                 || !TEST_true(find_session_cb_cnt == 0)
2926                 || !TEST_true(psk_client_cb_cnt == 2)
2927                 || !TEST_true(psk_server_cb_cnt == 2))
2928             goto end;
2929     }
2930
2931     shutdown_ssl_connection(serverssl, clientssl);
2932     serverssl = clientssl = NULL;
2933     use_session_cb_cnt = find_session_cb_cnt = 0;
2934     psk_client_cb_cnt = psk_server_cb_cnt = 0;
2935
2936     /*
2937      * Check that if the server rejects the PSK we can still connect, but with
2938      * a full handshake
2939      */
2940     srvid = "Dummy Identity";
2941     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2942                                              NULL, NULL))
2943             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2944                                                 SSL_ERROR_NONE))
2945             || !TEST_false(SSL_session_reused(clientssl))
2946             || !TEST_false(SSL_session_reused(serverssl)))
2947         goto end;
2948
2949     if (idx == 0 || idx == 1) {
2950         if (!TEST_true(use_session_cb_cnt == 1)
2951                 || !TEST_true(find_session_cb_cnt == 1)
2952                 || !TEST_true(psk_client_cb_cnt == 0)
2953                    /*
2954                     * If no old style callback then below should be 0
2955                     * otherwise 1
2956                     */
2957                 || !TEST_true(psk_server_cb_cnt == idx))
2958             goto end;
2959     } else {
2960         if (!TEST_true(use_session_cb_cnt == 0)
2961                 || !TEST_true(find_session_cb_cnt == 0)
2962                 || !TEST_true(psk_client_cb_cnt == 1)
2963                 || !TEST_true(psk_server_cb_cnt == 1))
2964             goto end;
2965     }
2966
2967     shutdown_ssl_connection(serverssl, clientssl);
2968     serverssl = clientssl = NULL;
2969     testresult = 1;
2970
2971  end:
2972     SSL_SESSION_free(clientpsk);
2973     SSL_SESSION_free(serverpsk);
2974     clientpsk = serverpsk = NULL;
2975     SSL_free(serverssl);
2976     SSL_free(clientssl);
2977     SSL_CTX_free(sctx);
2978     SSL_CTX_free(cctx);
2979     return testresult;
2980 }
2981
2982 static unsigned char cookie_magic_value[] = "cookie magic";
2983
2984 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
2985                                     unsigned int *cookie_len)
2986 {
2987     /*
2988      * Not suitable as a real cookie generation function but good enough for
2989      * testing!
2990      */
2991     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
2992     *cookie_len = sizeof(cookie_magic_value) - 1;
2993
2994     return 1;
2995 }
2996
2997 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
2998                                   unsigned int cookie_len)
2999 {
3000     if (cookie_len == sizeof(cookie_magic_value) - 1
3001         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
3002         return 1;
3003
3004     return 0;
3005 }
3006
3007 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
3008                                         size_t *cookie_len)
3009 {
3010     unsigned int temp;
3011     int res = generate_cookie_callback(ssl, cookie, &temp);
3012     *cookie_len = temp;
3013     return res;
3014 }
3015
3016 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
3017                                       size_t cookie_len)
3018 {
3019     return verify_cookie_callback(ssl, cookie, cookie_len);
3020 }
3021
3022 static int test_stateless(void)
3023 {
3024     SSL_CTX *sctx = NULL, *cctx = NULL;
3025     SSL *serverssl = NULL, *clientssl = NULL;
3026     int testresult = 0;
3027
3028     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3029                                        TLS1_VERSION, TLS_MAX_VERSION,
3030                                        &sctx, &cctx, cert, privkey)))
3031         goto end;
3032
3033     /* The arrival of CCS messages can confuse the test */
3034     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
3035
3036     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3037                                       NULL, NULL))
3038                /* Send the first ClientHello */
3039             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3040                                                  SSL_ERROR_WANT_READ))
3041                /*
3042                 * This should fail with a -1 return because we have no callbacks
3043                 * set up
3044                 */
3045             || !TEST_int_eq(SSL_stateless(serverssl), -1))
3046         goto end;
3047
3048     /* Fatal error so abandon the connection from this client */
3049     SSL_free(clientssl);
3050     clientssl = NULL;
3051
3052     /* Set up the cookie generation and verification callbacks */
3053     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
3054     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
3055
3056     /*
3057      * Create a new connection from the client (we can reuse the server SSL
3058      * object).
3059      */
3060     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3061                                              NULL, NULL))
3062                /* Send the first ClientHello */
3063             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3064                                                 SSL_ERROR_WANT_READ))
3065                /* This should fail because there is no cookie */
3066             || !TEST_int_eq(SSL_stateless(serverssl), 0))
3067         goto end;
3068
3069     /* Abandon the connection from this client */
3070     SSL_free(clientssl);
3071     clientssl = NULL;
3072
3073     /*
3074      * Now create a connection from a new client but with the same server SSL
3075      * object
3076      */
3077     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3078                                              NULL, NULL))
3079                /* Send the first ClientHello */
3080             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3081                                                 SSL_ERROR_WANT_READ))
3082                /* This should fail because there is no cookie */
3083             || !TEST_int_eq(SSL_stateless(serverssl), 0)
3084                /* Send the second ClientHello */
3085             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3086                                                 SSL_ERROR_WANT_READ))
3087                /* This should succeed because a cookie is now present */
3088             || !TEST_int_eq(SSL_stateless(serverssl), 1)
3089                /* Complete the connection */
3090             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3091                                                 SSL_ERROR_NONE)))
3092         goto end;
3093
3094     shutdown_ssl_connection(serverssl, clientssl);
3095     serverssl = clientssl = NULL;
3096     testresult = 1;
3097
3098  end:
3099     SSL_free(serverssl);
3100     SSL_free(clientssl);
3101     SSL_CTX_free(sctx);
3102     SSL_CTX_free(cctx);
3103     return testresult;
3104
3105 }
3106 #endif /* OPENSSL_NO_TLS1_3 */
3107
3108 static int clntaddoldcb = 0;
3109 static int clntparseoldcb = 0;
3110 static int srvaddoldcb = 0;
3111 static int srvparseoldcb = 0;
3112 static int clntaddnewcb = 0;
3113 static int clntparsenewcb = 0;
3114 static int srvaddnewcb = 0;
3115 static int srvparsenewcb = 0;
3116 static int snicb = 0;
3117
3118 #define TEST_EXT_TYPE1  0xff00
3119
3120 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
3121                       size_t *outlen, int *al, void *add_arg)
3122 {
3123     int *server = (int *)add_arg;
3124     unsigned char *data;
3125
3126     if (SSL_is_server(s))
3127         srvaddoldcb++;
3128     else
3129         clntaddoldcb++;
3130
3131     if (*server != SSL_is_server(s)
3132             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3133         return -1;
3134
3135     *data = 1;
3136     *out = data;
3137     *outlen = sizeof(char);
3138     return 1;
3139 }
3140
3141 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
3142                         void *add_arg)
3143 {
3144     OPENSSL_free((unsigned char *)out);
3145 }
3146
3147 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
3148                         size_t inlen, int *al, void *parse_arg)
3149 {
3150     int *server = (int *)parse_arg;
3151
3152     if (SSL_is_server(s))
3153         srvparseoldcb++;
3154     else
3155         clntparseoldcb++;
3156
3157     if (*server != SSL_is_server(s)
3158             || inlen != sizeof(char)
3159             || *in != 1)
3160         return -1;
3161
3162     return 1;
3163 }
3164
3165 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
3166                       const unsigned char **out, size_t *outlen, X509 *x,
3167                       size_t chainidx, int *al, void *add_arg)
3168 {
3169     int *server = (int *)add_arg;
3170     unsigned char *data;
3171
3172     if (SSL_is_server(s))
3173         srvaddnewcb++;
3174     else
3175         clntaddnewcb++;
3176
3177     if (*server != SSL_is_server(s)
3178             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3179         return -1;
3180
3181     *data = 1;
3182     *out = data;
3183     *outlen = sizeof(*data);
3184     return 1;
3185 }
3186
3187 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
3188                         const unsigned char *out, void *add_arg)
3189 {
3190     OPENSSL_free((unsigned char *)out);
3191 }
3192
3193 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
3194                         const unsigned char *in, size_t inlen, X509 *x,
3195                         size_t chainidx, int *al, void *parse_arg)
3196 {
3197     int *server = (int *)parse_arg;
3198
3199     if (SSL_is_server(s))
3200         srvparsenewcb++;
3201     else
3202         clntparsenewcb++;
3203
3204     if (*server != SSL_is_server(s)
3205             || inlen != sizeof(char) || *in != 1)
3206         return -1;
3207
3208     return 1;
3209 }
3210
3211 static int sni_cb(SSL *s, int *al, void *arg)
3212 {
3213     SSL_CTX *ctx = (SSL_CTX *)arg;
3214
3215     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
3216         *al = SSL_AD_INTERNAL_ERROR;
3217         return SSL_TLSEXT_ERR_ALERT_FATAL;
3218     }
3219     snicb++;
3220     return SSL_TLSEXT_ERR_OK;
3221 }
3222
3223 /*
3224  * Custom call back tests.
3225  * Test 0: Old style callbacks in TLSv1.2
3226  * Test 1: New style callbacks in TLSv1.2
3227  * Test 2: New style callbacks in TLSv1.2 with SNI
3228  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
3229  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
3230  */
3231 static int test_custom_exts(int tst)
3232 {
3233     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
3234     SSL *clientssl = NULL, *serverssl = NULL;
3235     int testresult = 0;
3236     static int server = 1;
3237     static int client = 0;
3238     SSL_SESSION *sess = NULL;
3239     unsigned int context;
3240
3241 #if defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_3)
3242     /* Skip tests for TLSv1.2 and below in this case */
3243     if (tst < 3)
3244         return 1;
3245 #endif
3246
3247     /* Reset callback counters */
3248     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
3249     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
3250     snicb = 0;
3251
3252     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3253                                        TLS1_VERSION, TLS_MAX_VERSION,
3254                                        &sctx, &cctx, cert, privkey)))
3255         goto end;
3256
3257     if (tst == 2
3258             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL,
3259                                               TLS1_VERSION, TLS_MAX_VERSION,
3260                                               &sctx2, NULL, cert, privkey)))
3261         goto end;
3262
3263
3264     if (tst < 3) {
3265         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
3266         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
3267         if (sctx2 != NULL)
3268             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
3269     }
3270
3271     if (tst == 4) {
3272         context = SSL_EXT_CLIENT_HELLO
3273                   | SSL_EXT_TLS1_2_SERVER_HELLO
3274                   | SSL_EXT_TLS1_3_SERVER_HELLO
3275                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
3276                   | SSL_EXT_TLS1_3_CERTIFICATE
3277                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
3278     } else {
3279         context = SSL_EXT_CLIENT_HELLO
3280                   | SSL_EXT_TLS1_2_SERVER_HELLO
3281                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
3282     }
3283
3284     /* Create a client side custom extension */
3285     if (tst == 0) {
3286         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3287                                                      old_add_cb, old_free_cb,
3288                                                      &client, old_parse_cb,
3289                                                      &client)))
3290             goto end;
3291     } else {
3292         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
3293                                               new_add_cb, new_free_cb,
3294                                               &client, new_parse_cb, &client)))
3295             goto end;
3296     }
3297
3298     /* Should not be able to add duplicates */
3299     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3300                                                   old_add_cb, old_free_cb,
3301                                                   &client, old_parse_cb,
3302                                                   &client))
3303             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
3304                                                   context, new_add_cb,
3305                                                   new_free_cb, &client,
3306                                                   new_parse_cb, &client)))
3307         goto end;
3308
3309     /* Create a server side custom extension */
3310     if (tst == 0) {
3311         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3312                                                      old_add_cb, old_free_cb,
3313                                                      &server, old_parse_cb,
3314                                                      &server)))
3315             goto end;
3316     } else {
3317         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
3318                                               new_add_cb, new_free_cb,
3319                                               &server, new_parse_cb, &server)))
3320             goto end;
3321         if (sctx2 != NULL
3322                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
3323                                                      context, new_add_cb,
3324                                                      new_free_cb, &server,
3325                                                      new_parse_cb, &server)))
3326             goto end;
3327     }
3328
3329     /* Should not be able to add duplicates */
3330     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3331                                                   old_add_cb, old_free_cb,
3332                                                   &server, old_parse_cb,
3333                                                   &server))
3334             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
3335                                                   context, new_add_cb,
3336                                                   new_free_cb, &server,
3337                                                   new_parse_cb, &server)))
3338         goto end;
3339
3340     if (tst == 2) {
3341         /* Set up SNI */
3342         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
3343                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
3344             goto end;
3345     }
3346
3347     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3348                                       &clientssl, NULL, NULL))
3349             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3350                                                 SSL_ERROR_NONE)))
3351         goto end;
3352
3353     if (tst == 0) {
3354         if (clntaddoldcb != 1
3355                 || clntparseoldcb != 1
3356                 || srvaddoldcb != 1
3357                 || srvparseoldcb != 1)
3358             goto end;
3359     } else if (tst == 1 || tst == 2 || tst == 3) {
3360         if (clntaddnewcb != 1
3361                 || clntparsenewcb != 1
3362                 || srvaddnewcb != 1
3363                 || srvparsenewcb != 1
3364                 || (tst != 2 && snicb != 0)
3365                 || (tst == 2 && snicb != 1))
3366             goto end;
3367     } else {
3368         if (clntaddnewcb != 1
3369                 || clntparsenewcb != 4
3370                 || srvaddnewcb != 4
3371                 || srvparsenewcb != 1)
3372             goto end;
3373     }
3374
3375     sess = SSL_get1_session(clientssl);
3376     SSL_shutdown(clientssl);
3377     SSL_shutdown(serverssl);
3378     SSL_free(serverssl);
3379     SSL_free(clientssl);
3380     serverssl = clientssl = NULL;
3381
3382     if (tst == 3) {
3383         /* We don't bother with the resumption aspects for this test */
3384         testresult = 1;
3385         goto end;
3386     }
3387
3388     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3389                                       NULL, NULL))
3390             || !TEST_true(SSL_set_session(clientssl, sess))
3391             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3392                                                SSL_ERROR_NONE)))
3393         goto end;
3394
3395     /*
3396      * For a resumed session we expect to add the ClientHello extension. For the
3397      * old style callbacks we ignore it on the server side because they set
3398      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
3399      * them.
3400      */
3401     if (tst == 0) {
3402         if (clntaddoldcb != 2
3403                 || clntparseoldcb != 1
3404                 || srvaddoldcb != 1
3405                 || srvparseoldcb != 1)
3406             goto end;
3407     } else if (tst == 1 || tst == 2 || tst == 3) {
3408         if (clntaddnewcb != 2
3409                 || clntparsenewcb != 2
3410                 || srvaddnewcb != 2
3411                 || srvparsenewcb != 2)
3412             goto end;
3413     } else {
3414         /* No Certificate message extensions in the resumption handshake */
3415         if (clntaddnewcb != 2
3416                 || clntparsenewcb != 7
3417                 || srvaddnewcb != 7
3418                 || srvparsenewcb != 2)
3419             goto end;
3420     }
3421
3422     testresult = 1;
3423
3424 end:
3425     SSL_SESSION_free(sess);
3426     SSL_free(serverssl);
3427     SSL_free(clientssl);
3428     SSL_CTX_free(sctx2);
3429     SSL_CTX_free(sctx);
3430     SSL_CTX_free(cctx);
3431     return testresult;
3432 }
3433
3434 /*
3435  * Test loading of serverinfo data in various formats. test_sslmessages actually
3436  * tests to make sure the extensions appear in the handshake
3437  */
3438 static int test_serverinfo(int tst)
3439 {
3440     unsigned int version;
3441     unsigned char *sibuf;
3442     size_t sibuflen;
3443     int ret, expected, testresult = 0;
3444     SSL_CTX *ctx;
3445
3446     ctx = SSL_CTX_new(TLS_method());
3447     if (!TEST_ptr(ctx))
3448         goto end;
3449
3450     if ((tst & 0x01) == 0x01)
3451         version = SSL_SERVERINFOV2;
3452     else
3453         version = SSL_SERVERINFOV1;
3454
3455     if ((tst & 0x02) == 0x02) {
3456         sibuf = serverinfov2;
3457         sibuflen = sizeof(serverinfov2);
3458         expected = (version == SSL_SERVERINFOV2);
3459     } else {
3460         sibuf = serverinfov1;
3461         sibuflen = sizeof(serverinfov1);
3462         expected = (version == SSL_SERVERINFOV1);
3463     }
3464
3465     if ((tst & 0x04) == 0x04) {
3466         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
3467     } else {
3468         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
3469
3470         /*
3471          * The version variable is irrelevant in this case - it's what is in the
3472          * buffer that matters
3473          */
3474         if ((tst & 0x02) == 0x02)
3475             expected = 0;
3476         else
3477             expected = 1;
3478     }
3479
3480     if (!TEST_true(ret == expected))
3481         goto end;
3482
3483     testresult = 1;
3484
3485  end:
3486     SSL_CTX_free(ctx);
3487
3488     return testresult;
3489 }
3490
3491 /*
3492  * Test that SSL_export_keying_material() produces expected results. There are
3493  * no test vectors so all we do is test that both sides of the communication
3494  * produce the same results for different protocol versions.
3495  */
3496 static int test_export_key_mat(int tst)
3497 {
3498     int testresult = 0;
3499     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
3500     SSL *clientssl = NULL, *serverssl = NULL;
3501     const char label[] = "test label";
3502     const unsigned char context[] = "context";
3503     const unsigned char *emptycontext = NULL;
3504     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
3505     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
3506     const int protocols[] = {
3507         TLS1_VERSION,
3508         TLS1_1_VERSION,
3509         TLS1_2_VERSION,
3510         TLS1_3_VERSION
3511     };
3512
3513 #ifdef OPENSSL_NO_TLS1
3514     if (tst == 0)
3515         return 1;
3516 #endif
3517 #ifdef OPENSSL_NO_TLS1_1
3518     if (tst == 1)
3519         return 1;
3520 #endif
3521 #ifdef OPENSSL_NO_TLS1_2
3522     if (tst == 2)
3523         return 1;
3524 #endif
3525 #ifdef OPENSSL_NO_TLS1_3
3526     if (tst == 3)
3527         return 1;
3528 #endif
3529     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3530                                        TLS1_VERSION, TLS_MAX_VERSION,
3531                                        &sctx, &cctx, cert, privkey)))
3532         goto end;
3533
3534     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
3535     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
3536     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
3537
3538     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
3539                                       NULL))
3540             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3541                                                 SSL_ERROR_NONE)))
3542         goto end;
3543
3544     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
3545                                                 sizeof(ckeymat1), label,
3546                                                 sizeof(label) - 1, context,
3547                                                 sizeof(context) - 1, 1), 1)
3548             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
3549                                                        sizeof(ckeymat2), label,
3550                                                        sizeof(label) - 1,
3551                                                        emptycontext,
3552                                                        0, 1), 1)
3553             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
3554                                                        sizeof(ckeymat3), label,
3555                                                        sizeof(label) - 1,
3556                                                        NULL, 0, 0), 1)
3557             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
3558                                                        sizeof(skeymat1), label,
3559                                                        sizeof(label) - 1,
3560                                                        context,
3561                                                        sizeof(context) -1, 1),
3562                             1)
3563             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
3564                                                        sizeof(skeymat2), label,
3565                                                        sizeof(label) - 1,
3566                                                        emptycontext,
3567                                                        0, 1), 1)
3568             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
3569                                                        sizeof(skeymat3), label,
3570                                                        sizeof(label) - 1,
3571                                                        NULL, 0, 0), 1)
3572                /*
3573                 * Check that both sides created the same key material with the
3574                 * same context.
3575                 */
3576             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
3577                             sizeof(skeymat1))
3578                /*
3579                 * Check that both sides created the same key material with an
3580                 * empty context.
3581                 */
3582             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
3583                             sizeof(skeymat2))
3584                /*
3585                 * Check that both sides created the same key material without a
3586                 * context.
3587                 */
3588             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
3589                             sizeof(skeymat3))
3590                /* Different contexts should produce different results */
3591             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
3592                             sizeof(ckeymat2)))
3593         goto end;
3594
3595     /*
3596      * Check that an empty context and no context produce different results in
3597      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
3598      */
3599     if ((tst != 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
3600                                   sizeof(ckeymat3)))
3601             || (tst ==3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
3602                                         sizeof(ckeymat3))))
3603         goto end;
3604
3605     testresult = 1;
3606
3607  end:
3608     SSL_free(serverssl);
3609     SSL_free(clientssl);
3610     SSL_CTX_free(sctx2);
3611     SSL_CTX_free(sctx);
3612     SSL_CTX_free(cctx);
3613
3614     return testresult;
3615 }
3616
3617 #ifndef OPENSSL_NO_TLS1_3
3618 /*
3619  * Test that SSL_export_keying_material_early() produces expected
3620  * results. There are no test vectors so all we do is test that both
3621  * sides of the communication produce the same results for different
3622  * protocol versions.
3623  */
3624 static int test_export_key_mat_early(int idx)
3625 {
3626     static const char label[] = "test label";
3627     static const unsigned char context[] = "context";
3628     int testresult = 0;
3629     SSL_CTX *cctx = NULL, *sctx = NULL;
3630     SSL *clientssl = NULL, *serverssl = NULL;
3631     SSL_SESSION *sess = NULL;
3632     const unsigned char *emptycontext = NULL;
3633     unsigned char ckeymat1[80], ckeymat2[80];
3634     unsigned char skeymat1[80], skeymat2[80];
3635     unsigned char buf[1];
3636     size_t readbytes, written;
3637
3638     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
3639                                         &sess, idx)))
3640         goto end;
3641
3642     /* Here writing 0 length early data is enough. */
3643     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
3644             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3645                                                 &readbytes),
3646                             SSL_READ_EARLY_DATA_ERROR)
3647             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3648                             SSL_EARLY_DATA_ACCEPTED))
3649         goto end;
3650
3651     if (!TEST_int_eq(SSL_export_keying_material_early(
3652                      clientssl, ckeymat1, sizeof(ckeymat1), label,
3653                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
3654             || !TEST_int_eq(SSL_export_keying_material_early(
3655                             clientssl, ckeymat2, sizeof(ckeymat2), label,
3656                             sizeof(label) - 1, emptycontext, 0), 1)
3657             || !TEST_int_eq(SSL_export_keying_material_early(
3658                             serverssl, skeymat1, sizeof(skeymat1), label,
3659                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
3660             || !TEST_int_eq(SSL_export_keying_material_early(
3661                             serverssl, skeymat2, sizeof(skeymat2), label,
3662                             sizeof(label) - 1, emptycontext, 0), 1)
3663                /*
3664                 * Check that both sides created the same key material with the
3665                 * same context.
3666                 */
3667             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
3668                             sizeof(skeymat1))
3669                /*
3670                 * Check that both sides created the same key material with an
3671                 * empty context.
3672                 */
3673             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
3674                             sizeof(skeymat2))
3675                /* Different contexts should produce different results */
3676             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
3677                             sizeof(ckeymat2)))
3678         goto end;
3679
3680     testresult = 1;
3681
3682  end:
3683     if (sess != clientpsk)
3684         SSL_SESSION_free(sess);
3685     SSL_SESSION_free(clientpsk);
3686     SSL_SESSION_free(serverpsk);
3687     clientpsk = serverpsk = NULL;
3688     SSL_free(serverssl);
3689     SSL_free(clientssl);
3690     SSL_CTX_free(sctx);
3691     SSL_CTX_free(cctx);
3692
3693     return testresult;
3694 }
3695 #endif /* OPENSSL_NO_TLS1_3 */
3696
3697 static int test_ssl_clear(int idx)
3698 {
3699     SSL_CTX *cctx = NULL, *sctx = NULL;
3700     SSL *clientssl = NULL, *serverssl = NULL;
3701     int testresult = 0;
3702
3703 #ifdef OPENSSL_NO_TLS1_2
3704     if (idx == 1)
3705         return 1;
3706 #endif
3707
3708     /* Create an initial connection */
3709     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3710                                        TLS1_VERSION, TLS_MAX_VERSION,
3711                                        &sctx, &cctx, cert, privkey))
3712             || (idx == 1
3713                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
3714                                                             TLS1_2_VERSION)))
3715             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3716                                           &clientssl, NULL, NULL))
3717             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3718                                                 SSL_ERROR_NONE)))
3719         goto end;
3720
3721     SSL_shutdown(clientssl);
3722     SSL_shutdown(serverssl);
3723     SSL_free(serverssl);
3724     serverssl = NULL;
3725
3726     /* Clear clientssl - we're going to reuse the object */
3727     if (!TEST_true(SSL_clear(clientssl)))
3728         goto end;
3729
3730     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3731                                              NULL, NULL))
3732             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3733                                                 SSL_ERROR_NONE))
3734             || !TEST_true(SSL_session_reused(clientssl)))
3735         goto end;
3736
3737     SSL_shutdown(clientssl);
3738     SSL_shutdown(serverssl);
3739
3740     testresult = 1;
3741
3742  end:
3743     SSL_free(serverssl);
3744     SSL_free(clientssl);
3745     SSL_CTX_free(sctx);
3746     SSL_CTX_free(cctx);
3747
3748     return testresult;
3749 }
3750
3751 /* Parse CH and retrieve any MFL extension value if present */
3752 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
3753 {
3754     long len;
3755     unsigned char *data;
3756     PACKET pkt = {0}, pkt2 = {0}, pkt3 = {0};
3757     unsigned int MFL_code = 0, type = 0;
3758
3759     if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
3760         goto end;
3761
3762     if (!TEST_true( PACKET_buf_init( &pkt, data, len ) )
3763                /* Skip the record header */
3764             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
3765                /* Skip the handshake message header */
3766             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
3767                /* Skip client version and random */
3768             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
3769                                                + SSL3_RANDOM_SIZE))
3770                /* Skip session id */
3771             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
3772                /* Skip ciphers */
3773             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
3774                /* Skip compression */
3775             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
3776                /* Extensions len */
3777             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
3778         goto end;
3779
3780     /* Loop through all extensions */
3781     while (PACKET_remaining(&pkt2)) {
3782         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
3783                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
3784             goto end;
3785
3786         if (type == TLSEXT_TYPE_max_fragment_length) {
3787             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
3788                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
3789                 goto end;
3790
3791             *mfl_codemfl_code = MFL_code;
3792             return 1;
3793         }
3794     }
3795
3796  end:
3797     return 0;
3798 }
3799
3800 /* Maximum-Fragment-Length TLS extension mode to test */
3801 static const unsigned char max_fragment_len_test[] = {
3802     TLSEXT_max_fragment_length_512,
3803     TLSEXT_max_fragment_length_1024,
3804     TLSEXT_max_fragment_length_2048,
3805     TLSEXT_max_fragment_length_4096
3806 };
3807
3808 static int test_max_fragment_len_ext(int idx_tst)
3809 {
3810     SSL_CTX *ctx;
3811     SSL *con = NULL;
3812     int testresult = 0, MFL_mode = 0;
3813     BIO *rbio, *wbio;
3814
3815     ctx = SSL_CTX_new(TLS_method());
3816     if (!TEST_ptr(ctx))
3817         goto end;
3818
3819     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
3820                    ctx, max_fragment_len_test[idx_tst])))
3821         goto end;
3822
3823     con = SSL_new(ctx);
3824     if (!TEST_ptr(con))
3825         goto end;
3826
3827     rbio = BIO_new(BIO_s_mem());
3828     wbio = BIO_new(BIO_s_mem());
3829     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
3830         BIO_free(rbio);
3831         BIO_free(wbio);
3832         goto end;
3833     }
3834
3835     SSL_set_bio(con, rbio, wbio);
3836     SSL_set_connect_state(con);
3837
3838     if (!TEST_int_le(SSL_connect(con), 0)) {
3839         /* This shouldn't succeed because we don't have a server! */
3840         goto end;
3841     }
3842
3843     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
3844         /* no MFL in client hello */
3845         goto end;
3846     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
3847         goto end;
3848
3849     testresult = 1;
3850
3851 end:
3852     SSL_free(con);
3853     SSL_CTX_free(ctx);
3854
3855     return testresult;
3856 }
3857
3858 #ifndef OPENSSL_NO_TLS1_3
3859 static int test_pha_key_update(void)
3860 {
3861     SSL_CTX *cctx = NULL, *sctx = NULL;
3862     SSL *clientssl = NULL, *serverssl = NULL;
3863     int testresult = 0;
3864
3865     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3866                                        TLS1_VERSION, TLS_MAX_VERSION,
3867                                        &sctx, &cctx, cert, privkey)))
3868         return 0;
3869
3870     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
3871         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
3872         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
3873         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
3874         goto end;
3875
3876
3877     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3878                                       NULL, NULL)))
3879         goto end;
3880
3881     SSL_force_post_handshake_auth(clientssl);
3882
3883     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
3884                                          SSL_ERROR_NONE)))
3885         goto end;
3886
3887     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
3888     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
3889         goto end;
3890
3891     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
3892         goto end;
3893
3894     /* Start handshake on the server */
3895     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
3896         goto end;
3897
3898     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
3899     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
3900                                          SSL_ERROR_NONE)))
3901         goto end;
3902
3903     SSL_shutdown(clientssl);
3904     SSL_shutdown(serverssl);
3905
3906     testresult = 1;
3907
3908  end:
3909     SSL_free(serverssl);
3910     SSL_free(clientssl);
3911     SSL_CTX_free(sctx);
3912     SSL_CTX_free(cctx);
3913     return testresult;
3914 }
3915 #endif
3916
3917 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
3918
3919 static SRP_VBASE *vbase = NULL;
3920
3921 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
3922 {
3923     int ret = SSL3_AL_FATAL;
3924     char *username;
3925     SRP_user_pwd *user = NULL;
3926
3927     username = SSL_get_srp_username(s);
3928     if (username == NULL) {
3929         *ad = SSL_AD_INTERNAL_ERROR;
3930         goto err;
3931     }
3932
3933     user = SRP_VBASE_get1_by_user(vbase, username);
3934     if (user == NULL) {
3935         *ad = SSL_AD_INTERNAL_ERROR;
3936         goto err;
3937     }
3938
3939     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
3940                                  user->info) <= 0) {
3941         *ad = SSL_AD_INTERNAL_ERROR;
3942         goto err;
3943     }
3944
3945     ret = 0;
3946
3947  err:
3948     SRP_user_pwd_free(user);
3949     return ret;
3950 }
3951
3952 static int create_new_vfile(char *userid, char *password, const char *filename)
3953 {
3954     char *gNid = NULL;
3955     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
3956     TXT_DB *db = NULL;
3957     int ret = 0;
3958     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
3959     size_t i;
3960
3961     if (!TEST_ptr(dummy) || !TEST_ptr(row))
3962         goto end;
3963
3964     gNid = SRP_create_verifier(userid, password, &row[DB_srpsalt],
3965                                &row[DB_srpverifier], NULL, NULL);
3966     if (!TEST_ptr(gNid))
3967         goto end;
3968
3969     /*
3970      * The only way to create an empty TXT_DB is to provide a BIO with no data
3971      * in it!
3972      */
3973     db = TXT_DB_read(dummy, DB_NUMBER);
3974     if (!TEST_ptr(db))
3975         goto end;
3976
3977     out = BIO_new_file(filename, "w");
3978     if (!TEST_ptr(out))
3979         goto end;
3980
3981     row[DB_srpid] = OPENSSL_strdup(userid);
3982     row[DB_srptype] = OPENSSL_strdup("V");
3983     row[DB_srpgN] = OPENSSL_strdup(gNid);
3984
3985     if (!TEST_ptr(row[DB_srpid])
3986             || !TEST_ptr(row[DB_srptype])
3987             || !TEST_ptr(row[DB_srpgN])
3988             || !TEST_true(TXT_DB_insert(db, row)))
3989         goto end;
3990
3991     row = NULL;
3992
3993     if (!TXT_DB_write(out, db))
3994         goto end;
3995
3996     ret = 1;
3997  end:
3998     if (row != NULL) {
3999         for (i = 0; i < DB_NUMBER; i++)
4000             OPENSSL_free(row[i]);
4001     }
4002     OPENSSL_free(row);
4003     BIO_free(dummy);
4004     BIO_free(out);
4005     TXT_DB_free(db);
4006
4007     return ret;
4008 }
4009
4010 static int create_new_vbase(char *userid, char *password)
4011 {
4012     BIGNUM *verifier = NULL, *salt = NULL;
4013     const SRP_gN *lgN = NULL;
4014     SRP_user_pwd *user_pwd = NULL;
4015     int ret = 0;
4016
4017     lgN = SRP_get_default_gN(NULL);
4018     if (!TEST_ptr(lgN))
4019         goto end;
4020
4021     if (!TEST_true(SRP_create_verifier_BN(userid, password, &salt, &verifier,
4022                                           lgN->N, lgN->g)))
4023         goto end;
4024
4025     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
4026     if (!TEST_ptr(user_pwd))
4027         goto end;
4028
4029     user_pwd->N = lgN->N;
4030     user_pwd->g = lgN->g;
4031     user_pwd->id = OPENSSL_strdup(userid);
4032     if (!TEST_ptr(user_pwd->id))
4033         goto end;
4034
4035     user_pwd->v = verifier;
4036     user_pwd->s = salt;
4037     verifier = salt = NULL;
4038
4039     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
4040         goto end;
4041     user_pwd = NULL;
4042
4043     ret = 1;
4044 end:
4045     SRP_user_pwd_free(user_pwd);
4046     BN_free(salt);
4047     BN_free(verifier);
4048
4049     return ret;
4050 }
4051
4052 /*
4053  * SRP tests
4054  *
4055  * Test 0: Simple successful SRP connection, new vbase
4056  * Test 1: Connection failure due to bad password, new vbase
4057  * Test 2: Simple successful SRP connection, vbase loaded from existing file
4058  * Test 3: Connection failure due to bad password, vbase loaded from existing
4059  *         file
4060  * Test 4: Simple successful SRP connection, vbase loaded from new file
4061  * Test 5: Connection failure due to bad password, vbase loaded from new file
4062  */
4063 static int test_srp(int tst)
4064 {
4065     char *userid = "test", *password = "password", *tstsrpfile;
4066     SSL_CTX *cctx = NULL, *sctx = NULL;
4067     SSL *clientssl = NULL, *serverssl = NULL;
4068     int ret, testresult = 0;
4069
4070     vbase = SRP_VBASE_new(NULL);
4071     if (!TEST_ptr(vbase))
4072         goto end;
4073
4074     if (tst == 0 || tst == 1) {
4075         if (!TEST_true(create_new_vbase(userid, password)))
4076             goto end;
4077     } else {
4078         if (tst == 4 || tst == 5) {
4079             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
4080                 goto end;
4081             tstsrpfile = tmpfilename;
4082         } else {
4083             tstsrpfile = srpvfile;
4084         }
4085         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
4086             goto end;
4087     }
4088
4089     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4090                                        TLS1_VERSION, TLS_MAX_VERSION,
4091                                        &sctx, &cctx, cert, privkey)))
4092         goto end;
4093
4094     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
4095             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
4096             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
4097             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
4098             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
4099         goto end;
4100
4101     if (tst % 2 == 1) {
4102         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
4103             goto end;
4104     } else {
4105         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
4106             goto end;
4107     }
4108
4109     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4110                                       NULL, NULL)))
4111         goto end;
4112
4113     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
4114     if (ret) {
4115         if (!TEST_true(tst % 2 == 0))
4116             goto end;
4117     } else {
4118         if (!TEST_true(tst % 2 == 1))
4119             goto end;
4120     }
4121
4122     testresult = 1;
4123
4124  end:
4125     SRP_VBASE_free(vbase);
4126     vbase = NULL;
4127     SSL_free(serverssl);
4128     SSL_free(clientssl);
4129     SSL_CTX_free(sctx);
4130     SSL_CTX_free(cctx);
4131
4132     return testresult;
4133 }
4134 #endif
4135
4136 static int info_cb_failed = 0;
4137 static int info_cb_offset = 0;
4138 static int info_cb_this_state = -1;
4139
4140 static struct info_cb_states_st {
4141     int where;
4142     const char *statestr;
4143 } info_cb_states[][60] = {
4144     {
4145         /* TLSv1.2 server followed by resumption */
4146         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4147         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4148         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
4149         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
4150         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
4151         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
4152         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4153         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4154         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
4155         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
4156         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
4157         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4158         {SSL_CB_EXIT, NULL}, {0, NULL},
4159     }, {
4160         /* TLSv1.2 client followed by resumption */
4161         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4162         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
4163         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
4164         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
4165         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
4166         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
4167         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
4168         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4169         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
4170         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
4171         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
4172         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4173     }, {
4174         /* TLSv1.3 server followed by resumption */
4175         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4176         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4177         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
4178         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
4179         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
4180         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4181         {SSL_CB_LOOP, "TWST"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4182         {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
4183         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4184         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4185         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
4186         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
4187         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4188         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TWST"},
4189         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4190     }, {
4191         /* TLSv1.3 client followed by resumption */
4192         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4193         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
4194         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
4195         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
4196         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
4197         {SSL_CB_EXIT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4198         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4199         {SSL_CB_HANDSHAKE_DONE, NULL},  {SSL_CB_EXIT, NULL},
4200         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4201         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
4202         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
4203         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
4204         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4205         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "SSLOK "},
4206         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4207         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4208     }, {
4209         /* TLSv1.3 server, early_data */
4210         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4211         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4212         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
4213         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4214         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
4215         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
4216         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4217         {SSL_CB_LOOP, "TWST"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4218         {SSL_CB_EXIT, NULL}, {0, NULL},
4219     }, {
4220         /* TLSv1.3 client, early_data */
4221         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4222         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
4223         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4224         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
4225         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
4226         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
4227         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4228         {SSL_CB_EXIT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4229         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4230         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4231     }, {
4232         {0, NULL},
4233     }
4234 };
4235
4236 static void sslapi_info_callback(const SSL *s, int where, int ret)
4237 {
4238     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
4239
4240     /* We do not ever expect a connection to fail in this test */
4241     if (!TEST_false(ret == 0)) {
4242         info_cb_failed = 1;
4243         return;
4244     }
4245
4246     /*
4247      * Do some sanity checks. We never expect these things to happen in this
4248      * test
4249      */
4250     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
4251             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
4252             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
4253         info_cb_failed = 1;
4254         return;
4255     }
4256
4257     /* Now check we're in the right state */
4258     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
4259         info_cb_failed = 1;
4260         return;
4261     }
4262     if ((where & SSL_CB_LOOP) != 0
4263             && !TEST_int_eq(strcmp(SSL_state_string(s),
4264                             state[info_cb_this_state].statestr), 0)) {
4265         info_cb_failed = 1;
4266         return;
4267     }
4268 }
4269
4270 /*
4271  * Test the info callback gets called when we expect it to.
4272  *
4273  * Test 0: TLSv1.2, server
4274  * Test 1: TLSv1.2, client
4275  * Test 2: TLSv1.3, server
4276  * Test 3: TLSv1.3, client
4277  * Test 4: TLSv1.3, server, early_data
4278  * Test 5: TLSv1.3, client, early_data
4279  */
4280 static int test_info_callback(int tst)
4281 {
4282     SSL_CTX *cctx = NULL, *sctx = NULL;
4283     SSL *clientssl = NULL, *serverssl = NULL;
4284     SSL_SESSION *clntsess = NULL;
4285     int testresult = 0;
4286     int tlsvers;
4287
4288     if (tst < 2) {
4289 #ifndef OPENSSL_NO_TLS1_2
4290         tlsvers = TLS1_2_VERSION;
4291 #else
4292         return 1;
4293 #endif
4294     } else {
4295 #ifndef OPENSSL_NO_TLS1_3
4296         tlsvers = TLS1_3_VERSION;
4297 #else
4298         return 1;
4299 #endif
4300     }
4301
4302     /* Reset globals */
4303     info_cb_failed = 0;
4304     info_cb_this_state = -1;
4305     info_cb_offset = tst;
4306
4307     if (tst >= 4) {
4308         SSL_SESSION *sess = NULL;
4309         size_t written, readbytes;
4310         unsigned char buf[80];
4311
4312         /* early_data tests */
4313         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4314                                             &serverssl, &sess, 0)))
4315             goto end;
4316
4317         /* We don't actually need this reference */
4318         SSL_SESSION_free(sess);
4319
4320         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
4321                               sslapi_info_callback);
4322
4323         /* Write and read some early data and then complete the connection */
4324         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4325                                             &written))
4326                 || !TEST_size_t_eq(written, strlen(MSG1))
4327                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
4328                                                     sizeof(buf), &readbytes),
4329                                 SSL_READ_EARLY_DATA_SUCCESS)
4330                 || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
4331                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4332                                 SSL_EARLY_DATA_ACCEPTED)
4333                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
4334                                                     SSL_ERROR_NONE))
4335                 || !TEST_false(info_cb_failed))
4336             goto end;
4337
4338         testresult = 1;
4339         goto end;
4340     }
4341
4342     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4343                                        TLS_client_method(),
4344                                        tlsvers, tlsvers, &sctx, &cctx, cert,
4345                                        privkey)))
4346         goto end;
4347
4348     /*
4349      * For even numbered tests we check the server callbacks. For odd numbers we
4350      * check the client.
4351      */
4352     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
4353                               sslapi_info_callback);
4354
4355     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4356                                           &clientssl, NULL, NULL))
4357         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4358                                             SSL_ERROR_NONE))
4359         || !TEST_false(info_cb_failed))
4360     goto end;
4361
4362
4363
4364     clntsess = SSL_get1_session(clientssl);
4365     SSL_shutdown(clientssl);
4366     SSL_shutdown(serverssl);
4367     SSL_free(serverssl);
4368     SSL_free(clientssl);
4369     serverssl = clientssl = NULL;
4370
4371     /* Now do a resumption */
4372     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
4373                                       NULL))
4374             || !TEST_true(SSL_set_session(clientssl, clntsess))
4375             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4376                                                 SSL_ERROR_NONE))
4377             || !TEST_true(SSL_session_reused(clientssl))
4378             || !TEST_false(info_cb_failed))
4379         goto end;
4380
4381     testresult = 1;
4382
4383  end:
4384     SSL_free(serverssl);
4385     SSL_free(clientssl);
4386     SSL_SESSION_free(clntsess);
4387     SSL_CTX_free(sctx);
4388     SSL_CTX_free(cctx);
4389     return testresult;
4390 }
4391
4392 int setup_tests(void)
4393 {
4394     if (!TEST_ptr(cert = test_get_argument(0))
4395             || !TEST_ptr(privkey = test_get_argument(1))
4396             || !TEST_ptr(srpvfile = test_get_argument(2))
4397             || !TEST_ptr(tmpfilename = test_get_argument(3)))
4398         return 0;
4399
4400     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
4401 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
4402         TEST_error("not supported in this build");
4403         return 0;
4404 #else
4405         int i, mcount, rcount, fcount;
4406
4407         for (i = 0; i < 4; i++)
4408             test_export_key_mat(i);
4409         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
4410         test_printf_stdout("malloc %d realloc %d free %d\n",
4411                 mcount, rcount, fcount);
4412         return 1;
4413 #endif
4414     }
4415
4416     ADD_TEST(test_large_message_tls);
4417     ADD_TEST(test_large_message_tls_read_ahead);
4418 #ifndef OPENSSL_NO_DTLS
4419     ADD_TEST(test_large_message_dtls);
4420 #endif
4421 #ifndef OPENSSL_NO_OCSP
4422     ADD_TEST(test_tlsext_status_type);
4423 #endif
4424     ADD_TEST(test_session_with_only_int_cache);
4425     ADD_TEST(test_session_with_only_ext_cache);
4426     ADD_TEST(test_session_with_both_cache);
4427     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
4428     ADD_TEST(test_ssl_bio_pop_next_bio);
4429     ADD_TEST(test_ssl_bio_pop_ssl_bio);
4430     ADD_TEST(test_ssl_bio_change_rbio);
4431     ADD_TEST(test_ssl_bio_change_wbio);
4432 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
4433     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
4434     ADD_TEST(test_keylog);
4435 #endif
4436 #ifndef OPENSSL_NO_TLS1_3
4437     ADD_TEST(test_keylog_no_master_key);
4438 #endif
4439 #ifndef OPENSSL_NO_TLS1_2
4440     ADD_TEST(test_client_hello_cb);
4441 #endif
4442 #ifndef OPENSSL_NO_TLS1_3
4443     ADD_ALL_TESTS(test_early_data_read_write, 3);
4444     /*
4445      * We don't do replay tests for external PSK. Replay protection isn't used
4446      * in that scenario.
4447      */
4448     ADD_ALL_TESTS(test_early_data_replay, 2);
4449     ADD_ALL_TESTS(test_early_data_skip, 3);
4450     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
4451     ADD_ALL_TESTS(test_early_data_not_sent, 3);
4452     ADD_ALL_TESTS(test_early_data_psk, 8);
4453     ADD_ALL_TESTS(test_early_data_not_expected, 3);
4454 # ifndef OPENSSL_NO_TLS1_2
4455     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
4456 # endif
4457 #endif
4458 #ifndef OPENSSL_NO_TLS1_3
4459     ADD_ALL_TESTS(test_set_ciphersuite, 10);
4460     ADD_TEST(test_ciphersuite_change);
4461 #ifdef OPENSSL_NO_PSK
4462     ADD_ALL_TESTS(test_tls13_psk, 1);
4463 #else
4464     ADD_ALL_TESTS(test_tls13_psk, 3);
4465 #endif  /* OPENSSL_NO_PSK */
4466     ADD_ALL_TESTS(test_custom_exts, 5);
4467     ADD_TEST(test_stateless);
4468     ADD_TEST(test_pha_key_update);
4469 #else
4470     ADD_ALL_TESTS(test_custom_exts, 3);
4471 #endif
4472     ADD_ALL_TESTS(test_serverinfo, 8);
4473     ADD_ALL_TESTS(test_export_key_mat, 4);
4474 #ifndef OPENSSL_NO_TLS1_3
4475     ADD_ALL_TESTS(test_export_key_mat_early, 3);
4476 #endif
4477     ADD_ALL_TESTS(test_ssl_clear, 2);
4478     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
4479 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
4480     ADD_ALL_TESTS(test_srp, 6);
4481 #endif
4482     ADD_ALL_TESTS(test_info_callback, 6);
4483     return 1;
4484 }
4485
4486 void cleanup_tests(void)
4487 {
4488     bio_s_mempacket_test_free();
4489 }