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