Test an old style PSK callback with no cert will prefer SHA-256
[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 /*
2785  * Test TLSv1.3 PSKs
2786  * Test 0 = Test new style callbacks
2787  * Test 1 = Test both new and old style callbacks
2788  * Test 2 = Test old style callbacks
2789  * Test 3 = Test old style callbacks with no certificate
2790  */
2791 static int test_tls13_psk(int idx)
2792 {
2793     SSL_CTX *sctx = NULL, *cctx = NULL;
2794     SSL *serverssl = NULL, *clientssl = NULL;
2795     const SSL_CIPHER *cipher = NULL;
2796     const unsigned char key[] = {
2797         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
2798         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
2799         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
2800         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
2801     };
2802     int testresult = 0;
2803
2804     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2805                                        TLS1_VERSION, TLS_MAX_VERSION,
2806                                        &sctx, &cctx, idx == 3 ? NULL : cert,
2807                                        idx == 3 ? NULL : privkey)))
2808         goto end;
2809
2810     if (idx != 3) {
2811         /*
2812          * We use a ciphersuite with SHA256 to ease testing old style PSK
2813          * callbacks which will always default to SHA256. This should not be
2814          * necessary if we have no cert/priv key. In that case the server should
2815          * prefer SHA256 automatically.
2816          */
2817         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2818                                                 "TLS_AES_128_GCM_SHA256")))
2819             goto end;
2820     }
2821
2822     /*
2823      * Test 0: New style callbacks only
2824      * Test 1: New and old style callbacks (only the new ones should be used)
2825      * Test 2: Old style callbacks only
2826      */
2827     if (idx == 0 || idx == 1) {
2828         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2829         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2830     }
2831 #ifndef OPENSSL_NO_PSK
2832     if (idx >= 1) {
2833         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
2834         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
2835     }
2836 #endif
2837     srvid = pskid;
2838     use_session_cb_cnt = 0;
2839     find_session_cb_cnt = 0;
2840     psk_client_cb_cnt = 0;
2841     psk_server_cb_cnt = 0;
2842
2843     if (idx != 3) {
2844         /*
2845          * Check we can create a connection if callback decides not to send a
2846          * PSK
2847          */
2848         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2849                                                  NULL, NULL))
2850                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
2851                                                     SSL_ERROR_NONE))
2852                 || !TEST_false(SSL_session_reused(clientssl))
2853                 || !TEST_false(SSL_session_reused(serverssl)))
2854             goto end;
2855
2856         if (idx == 0 || idx == 1) {
2857             if (!TEST_true(use_session_cb_cnt == 1)
2858                     || !TEST_true(find_session_cb_cnt == 0)
2859                        /*
2860                         * If no old style callback then below should be 0
2861                         * otherwise 1
2862                         */
2863                     || !TEST_true(psk_client_cb_cnt == idx)
2864                     || !TEST_true(psk_server_cb_cnt == 0))
2865                 goto end;
2866         } else {
2867             if (!TEST_true(use_session_cb_cnt == 0)
2868                     || !TEST_true(find_session_cb_cnt == 0)
2869                     || !TEST_true(psk_client_cb_cnt == 1)
2870                     || !TEST_true(psk_server_cb_cnt == 0))
2871                 goto end;
2872         }
2873
2874         shutdown_ssl_connection(serverssl, clientssl);
2875         serverssl = clientssl = NULL;
2876         use_session_cb_cnt = psk_client_cb_cnt = 0;
2877     }
2878
2879     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2880                                              NULL, NULL)))
2881         goto end;
2882
2883     /* Create the PSK */
2884     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
2885     clientpsk = SSL_SESSION_new();
2886     if (!TEST_ptr(clientpsk)
2887             || !TEST_ptr(cipher)
2888             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
2889                                                       sizeof(key)))
2890             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
2891             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
2892                                                            TLS1_3_VERSION))
2893             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
2894         goto end;
2895     serverpsk = clientpsk;
2896
2897     /* Check we can create a connection and the PSK is used */
2898     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2899             || !TEST_true(SSL_session_reused(clientssl))
2900             || !TEST_true(SSL_session_reused(serverssl)))
2901         goto end;
2902
2903     if (idx == 0 || idx == 1) {
2904         if (!TEST_true(use_session_cb_cnt == 1)
2905                 || !TEST_true(find_session_cb_cnt == 1)
2906                 || !TEST_true(psk_client_cb_cnt == 0)
2907                 || !TEST_true(psk_server_cb_cnt == 0))
2908             goto end;
2909     } else {
2910         if (!TEST_true(use_session_cb_cnt == 0)
2911                 || !TEST_true(find_session_cb_cnt == 0)
2912                 || !TEST_true(psk_client_cb_cnt == 1)
2913                 || !TEST_true(psk_server_cb_cnt == 1))
2914             goto end;
2915     }
2916
2917     shutdown_ssl_connection(serverssl, clientssl);
2918     serverssl = clientssl = NULL;
2919     use_session_cb_cnt = find_session_cb_cnt = 0;
2920     psk_client_cb_cnt = psk_server_cb_cnt = 0;
2921
2922     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2923                                              NULL, NULL)))
2924         goto end;
2925
2926     /* Force an HRR */
2927     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2928         goto end;
2929
2930     /*
2931      * Check we can create a connection, the PSK is used and the callbacks are
2932      * called twice.
2933      */
2934     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2935             || !TEST_true(SSL_session_reused(clientssl))
2936             || !TEST_true(SSL_session_reused(serverssl)))
2937         goto end;
2938
2939     if (idx == 0 || idx == 1) {
2940         if (!TEST_true(use_session_cb_cnt == 2)
2941                 || !TEST_true(find_session_cb_cnt == 2)
2942                 || !TEST_true(psk_client_cb_cnt == 0)
2943                 || !TEST_true(psk_server_cb_cnt == 0))
2944             goto end;
2945     } else {
2946         if (!TEST_true(use_session_cb_cnt == 0)
2947                 || !TEST_true(find_session_cb_cnt == 0)
2948                 || !TEST_true(psk_client_cb_cnt == 2)
2949                 || !TEST_true(psk_server_cb_cnt == 2))
2950             goto end;
2951     }
2952
2953     shutdown_ssl_connection(serverssl, clientssl);
2954     serverssl = clientssl = NULL;
2955     use_session_cb_cnt = find_session_cb_cnt = 0;
2956     psk_client_cb_cnt = psk_server_cb_cnt = 0;
2957
2958     if (idx != 3) {
2959         /*
2960          * Check that if the server rejects the PSK we can still connect, but with
2961          * a full handshake
2962          */
2963         srvid = "Dummy Identity";
2964         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2965                                                  NULL, NULL))
2966                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
2967                                                     SSL_ERROR_NONE))
2968                 || !TEST_false(SSL_session_reused(clientssl))
2969                 || !TEST_false(SSL_session_reused(serverssl)))
2970             goto end;
2971
2972         if (idx == 0 || idx == 1) {
2973             if (!TEST_true(use_session_cb_cnt == 1)
2974                     || !TEST_true(find_session_cb_cnt == 1)
2975                     || !TEST_true(psk_client_cb_cnt == 0)
2976                        /*
2977                         * If no old style callback then below should be 0
2978                         * otherwise 1
2979                         */
2980                     || !TEST_true(psk_server_cb_cnt == idx))
2981                 goto end;
2982         } else {
2983             if (!TEST_true(use_session_cb_cnt == 0)
2984                     || !TEST_true(find_session_cb_cnt == 0)
2985                     || !TEST_true(psk_client_cb_cnt == 1)
2986                     || !TEST_true(psk_server_cb_cnt == 1))
2987                 goto end;
2988         }
2989
2990         shutdown_ssl_connection(serverssl, clientssl);
2991         serverssl = clientssl = NULL;
2992     }
2993     testresult = 1;
2994
2995  end:
2996     SSL_SESSION_free(clientpsk);
2997     SSL_SESSION_free(serverpsk);
2998     clientpsk = serverpsk = NULL;
2999     SSL_free(serverssl);
3000     SSL_free(clientssl);
3001     SSL_CTX_free(sctx);
3002     SSL_CTX_free(cctx);
3003     return testresult;
3004 }
3005
3006 static unsigned char cookie_magic_value[] = "cookie magic";
3007
3008 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
3009                                     unsigned int *cookie_len)
3010 {
3011     /*
3012      * Not suitable as a real cookie generation function but good enough for
3013      * testing!
3014      */
3015     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
3016     *cookie_len = sizeof(cookie_magic_value) - 1;
3017
3018     return 1;
3019 }
3020
3021 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
3022                                   unsigned int cookie_len)
3023 {
3024     if (cookie_len == sizeof(cookie_magic_value) - 1
3025         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
3026         return 1;
3027
3028     return 0;
3029 }
3030
3031 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
3032                                         size_t *cookie_len)
3033 {
3034     unsigned int temp;
3035     int res = generate_cookie_callback(ssl, cookie, &temp);
3036     *cookie_len = temp;
3037     return res;
3038 }
3039
3040 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
3041                                       size_t cookie_len)
3042 {
3043     return verify_cookie_callback(ssl, cookie, cookie_len);
3044 }
3045
3046 static int test_stateless(void)
3047 {
3048     SSL_CTX *sctx = NULL, *cctx = NULL;
3049     SSL *serverssl = NULL, *clientssl = NULL;
3050     int testresult = 0;
3051
3052     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3053                                        TLS1_VERSION, TLS_MAX_VERSION,
3054                                        &sctx, &cctx, cert, privkey)))
3055         goto end;
3056
3057     /* The arrival of CCS messages can confuse the test */
3058     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
3059
3060     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3061                                       NULL, NULL))
3062                /* Send the first ClientHello */
3063             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3064                                                  SSL_ERROR_WANT_READ))
3065                /*
3066                 * This should fail with a -1 return because we have no callbacks
3067                 * set up
3068                 */
3069             || !TEST_int_eq(SSL_stateless(serverssl), -1))
3070         goto end;
3071
3072     /* Fatal error so abandon the connection from this client */
3073     SSL_free(clientssl);
3074     clientssl = NULL;
3075
3076     /* Set up the cookie generation and verification callbacks */
3077     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
3078     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
3079
3080     /*
3081      * Create a new connection from the client (we can reuse the server SSL
3082      * object).
3083      */
3084     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3085                                              NULL, NULL))
3086                /* Send the first ClientHello */
3087             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3088                                                 SSL_ERROR_WANT_READ))
3089                /* This should fail because there is no cookie */
3090             || !TEST_int_eq(SSL_stateless(serverssl), 0))
3091         goto end;
3092
3093     /* Abandon the connection from this client */
3094     SSL_free(clientssl);
3095     clientssl = NULL;
3096
3097     /*
3098      * Now create a connection from a new client but with the same server SSL
3099      * object
3100      */
3101     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3102                                              NULL, NULL))
3103                /* Send the first ClientHello */
3104             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3105                                                 SSL_ERROR_WANT_READ))
3106                /* This should fail because there is no cookie */
3107             || !TEST_int_eq(SSL_stateless(serverssl), 0)
3108                /* Send the second ClientHello */
3109             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3110                                                 SSL_ERROR_WANT_READ))
3111                /* This should succeed because a cookie is now present */
3112             || !TEST_int_eq(SSL_stateless(serverssl), 1)
3113                /* Complete the connection */
3114             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3115                                                 SSL_ERROR_NONE)))
3116         goto end;
3117
3118     shutdown_ssl_connection(serverssl, clientssl);
3119     serverssl = clientssl = NULL;
3120     testresult = 1;
3121
3122  end:
3123     SSL_free(serverssl);
3124     SSL_free(clientssl);
3125     SSL_CTX_free(sctx);
3126     SSL_CTX_free(cctx);
3127     return testresult;
3128
3129 }
3130 #endif /* OPENSSL_NO_TLS1_3 */
3131
3132 static int clntaddoldcb = 0;
3133 static int clntparseoldcb = 0;
3134 static int srvaddoldcb = 0;
3135 static int srvparseoldcb = 0;
3136 static int clntaddnewcb = 0;
3137 static int clntparsenewcb = 0;
3138 static int srvaddnewcb = 0;
3139 static int srvparsenewcb = 0;
3140 static int snicb = 0;
3141
3142 #define TEST_EXT_TYPE1  0xff00
3143
3144 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
3145                       size_t *outlen, int *al, void *add_arg)
3146 {
3147     int *server = (int *)add_arg;
3148     unsigned char *data;
3149
3150     if (SSL_is_server(s))
3151         srvaddoldcb++;
3152     else
3153         clntaddoldcb++;
3154
3155     if (*server != SSL_is_server(s)
3156             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3157         return -1;
3158
3159     *data = 1;
3160     *out = data;
3161     *outlen = sizeof(char);
3162     return 1;
3163 }
3164
3165 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
3166                         void *add_arg)
3167 {
3168     OPENSSL_free((unsigned char *)out);
3169 }
3170
3171 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
3172                         size_t inlen, int *al, void *parse_arg)
3173 {
3174     int *server = (int *)parse_arg;
3175
3176     if (SSL_is_server(s))
3177         srvparseoldcb++;
3178     else
3179         clntparseoldcb++;
3180
3181     if (*server != SSL_is_server(s)
3182             || inlen != sizeof(char)
3183             || *in != 1)
3184         return -1;
3185
3186     return 1;
3187 }
3188
3189 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
3190                       const unsigned char **out, size_t *outlen, X509 *x,
3191                       size_t chainidx, int *al, void *add_arg)
3192 {
3193     int *server = (int *)add_arg;
3194     unsigned char *data;
3195
3196     if (SSL_is_server(s))
3197         srvaddnewcb++;
3198     else
3199         clntaddnewcb++;
3200
3201     if (*server != SSL_is_server(s)
3202             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3203         return -1;
3204
3205     *data = 1;
3206     *out = data;
3207     *outlen = sizeof(*data);
3208     return 1;
3209 }
3210
3211 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
3212                         const unsigned char *out, void *add_arg)
3213 {
3214     OPENSSL_free((unsigned char *)out);
3215 }
3216
3217 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
3218                         const unsigned char *in, size_t inlen, X509 *x,
3219                         size_t chainidx, int *al, void *parse_arg)
3220 {
3221     int *server = (int *)parse_arg;
3222
3223     if (SSL_is_server(s))
3224         srvparsenewcb++;
3225     else
3226         clntparsenewcb++;
3227
3228     if (*server != SSL_is_server(s)
3229             || inlen != sizeof(char) || *in != 1)
3230         return -1;
3231
3232     return 1;
3233 }
3234
3235 static int sni_cb(SSL *s, int *al, void *arg)
3236 {
3237     SSL_CTX *ctx = (SSL_CTX *)arg;
3238
3239     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
3240         *al = SSL_AD_INTERNAL_ERROR;
3241         return SSL_TLSEXT_ERR_ALERT_FATAL;
3242     }
3243     snicb++;
3244     return SSL_TLSEXT_ERR_OK;
3245 }
3246
3247 /*
3248  * Custom call back tests.
3249  * Test 0: Old style callbacks in TLSv1.2
3250  * Test 1: New style callbacks in TLSv1.2
3251  * Test 2: New style callbacks in TLSv1.2 with SNI
3252  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
3253  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
3254  */
3255 static int test_custom_exts(int tst)
3256 {
3257     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
3258     SSL *clientssl = NULL, *serverssl = NULL;
3259     int testresult = 0;
3260     static int server = 1;
3261     static int client = 0;
3262     SSL_SESSION *sess = NULL;
3263     unsigned int context;
3264
3265 #if defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_3)
3266     /* Skip tests for TLSv1.2 and below in this case */
3267     if (tst < 3)
3268         return 1;
3269 #endif
3270
3271     /* Reset callback counters */
3272     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
3273     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
3274     snicb = 0;
3275
3276     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3277                                        TLS1_VERSION, TLS_MAX_VERSION,
3278                                        &sctx, &cctx, cert, privkey)))
3279         goto end;
3280
3281     if (tst == 2
3282             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL,
3283                                               TLS1_VERSION, TLS_MAX_VERSION,
3284                                               &sctx2, NULL, cert, privkey)))
3285         goto end;
3286
3287
3288     if (tst < 3) {
3289         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
3290         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
3291         if (sctx2 != NULL)
3292             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
3293     }
3294
3295     if (tst == 4) {
3296         context = SSL_EXT_CLIENT_HELLO
3297                   | SSL_EXT_TLS1_2_SERVER_HELLO
3298                   | SSL_EXT_TLS1_3_SERVER_HELLO
3299                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
3300                   | SSL_EXT_TLS1_3_CERTIFICATE
3301                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
3302     } else {
3303         context = SSL_EXT_CLIENT_HELLO
3304                   | SSL_EXT_TLS1_2_SERVER_HELLO
3305                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
3306     }
3307
3308     /* Create a client side custom extension */
3309     if (tst == 0) {
3310         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3311                                                      old_add_cb, old_free_cb,
3312                                                      &client, old_parse_cb,
3313                                                      &client)))
3314             goto end;
3315     } else {
3316         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
3317                                               new_add_cb, new_free_cb,
3318                                               &client, new_parse_cb, &client)))
3319             goto end;
3320     }
3321
3322     /* Should not be able to add duplicates */
3323     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3324                                                   old_add_cb, old_free_cb,
3325                                                   &client, old_parse_cb,
3326                                                   &client))
3327             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
3328                                                   context, new_add_cb,
3329                                                   new_free_cb, &client,
3330                                                   new_parse_cb, &client)))
3331         goto end;
3332
3333     /* Create a server side custom extension */
3334     if (tst == 0) {
3335         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3336                                                      old_add_cb, old_free_cb,
3337                                                      &server, old_parse_cb,
3338                                                      &server)))
3339             goto end;
3340     } else {
3341         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
3342                                               new_add_cb, new_free_cb,
3343                                               &server, new_parse_cb, &server)))
3344             goto end;
3345         if (sctx2 != NULL
3346                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
3347                                                      context, new_add_cb,
3348                                                      new_free_cb, &server,
3349                                                      new_parse_cb, &server)))
3350             goto end;
3351     }
3352
3353     /* Should not be able to add duplicates */
3354     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3355                                                   old_add_cb, old_free_cb,
3356                                                   &server, old_parse_cb,
3357                                                   &server))
3358             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
3359                                                   context, new_add_cb,
3360                                                   new_free_cb, &server,
3361                                                   new_parse_cb, &server)))
3362         goto end;
3363
3364     if (tst == 2) {
3365         /* Set up SNI */
3366         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
3367                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
3368             goto end;
3369     }
3370
3371     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3372                                       &clientssl, NULL, NULL))
3373             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3374                                                 SSL_ERROR_NONE)))
3375         goto end;
3376
3377     if (tst == 0) {
3378         if (clntaddoldcb != 1
3379                 || clntparseoldcb != 1
3380                 || srvaddoldcb != 1
3381                 || srvparseoldcb != 1)
3382             goto end;
3383     } else if (tst == 1 || tst == 2 || tst == 3) {
3384         if (clntaddnewcb != 1
3385                 || clntparsenewcb != 1
3386                 || srvaddnewcb != 1
3387                 || srvparsenewcb != 1
3388                 || (tst != 2 && snicb != 0)
3389                 || (tst == 2 && snicb != 1))
3390             goto end;
3391     } else {
3392         if (clntaddnewcb != 1
3393                 || clntparsenewcb != 4
3394                 || srvaddnewcb != 4
3395                 || srvparsenewcb != 1)
3396             goto end;
3397     }
3398
3399     sess = SSL_get1_session(clientssl);
3400     SSL_shutdown(clientssl);
3401     SSL_shutdown(serverssl);
3402     SSL_free(serverssl);
3403     SSL_free(clientssl);
3404     serverssl = clientssl = NULL;
3405
3406     if (tst == 3) {
3407         /* We don't bother with the resumption aspects for this test */
3408         testresult = 1;
3409         goto end;
3410     }
3411
3412     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3413                                       NULL, NULL))
3414             || !TEST_true(SSL_set_session(clientssl, sess))
3415             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3416                                                SSL_ERROR_NONE)))
3417         goto end;
3418
3419     /*
3420      * For a resumed session we expect to add the ClientHello extension. For the
3421      * old style callbacks we ignore it on the server side because they set
3422      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
3423      * them.
3424      */
3425     if (tst == 0) {
3426         if (clntaddoldcb != 2
3427                 || clntparseoldcb != 1
3428                 || srvaddoldcb != 1
3429                 || srvparseoldcb != 1)
3430             goto end;
3431     } else if (tst == 1 || tst == 2 || tst == 3) {
3432         if (clntaddnewcb != 2
3433                 || clntparsenewcb != 2
3434                 || srvaddnewcb != 2
3435                 || srvparsenewcb != 2)
3436             goto end;
3437     } else {
3438         /* No Certificate message extensions in the resumption handshake */
3439         if (clntaddnewcb != 2
3440                 || clntparsenewcb != 7
3441                 || srvaddnewcb != 7
3442                 || srvparsenewcb != 2)
3443             goto end;
3444     }
3445
3446     testresult = 1;
3447
3448 end:
3449     SSL_SESSION_free(sess);
3450     SSL_free(serverssl);
3451     SSL_free(clientssl);
3452     SSL_CTX_free(sctx2);
3453     SSL_CTX_free(sctx);
3454     SSL_CTX_free(cctx);
3455     return testresult;
3456 }
3457
3458 /*
3459  * Test loading of serverinfo data in various formats. test_sslmessages actually
3460  * tests to make sure the extensions appear in the handshake
3461  */
3462 static int test_serverinfo(int tst)
3463 {
3464     unsigned int version;
3465     unsigned char *sibuf;
3466     size_t sibuflen;
3467     int ret, expected, testresult = 0;
3468     SSL_CTX *ctx;
3469
3470     ctx = SSL_CTX_new(TLS_method());
3471     if (!TEST_ptr(ctx))
3472         goto end;
3473
3474     if ((tst & 0x01) == 0x01)
3475         version = SSL_SERVERINFOV2;
3476     else
3477         version = SSL_SERVERINFOV1;
3478
3479     if ((tst & 0x02) == 0x02) {
3480         sibuf = serverinfov2;
3481         sibuflen = sizeof(serverinfov2);
3482         expected = (version == SSL_SERVERINFOV2);
3483     } else {
3484         sibuf = serverinfov1;
3485         sibuflen = sizeof(serverinfov1);
3486         expected = (version == SSL_SERVERINFOV1);
3487     }
3488
3489     if ((tst & 0x04) == 0x04) {
3490         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
3491     } else {
3492         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
3493
3494         /*
3495          * The version variable is irrelevant in this case - it's what is in the