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