8cc493406bf1a77657aaa5f7760b4e6d6d08acae
[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_test(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_test(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_test(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     SSL_CTX_free(sctx);
1370     SSL_CTX_free(cctx);
1371     sctx = cctx = NULL;
1372
1373     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
1374         goto end;
1375
1376     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1377                                           &clientssl, NULL, NULL)))
1378         goto end;
1379
1380     SSL_force_post_handshake_auth(clientssl);
1381
1382     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1383                                                 SSL_ERROR_NONE))
1384                /* Check we got the number of tickets we were expecting */
1385             || !TEST_int_eq(idx, new_called))
1386         goto end;
1387
1388     /* After a post-handshake authentication we should get new tickets issued */
1389     if (!post_handshake_verify(serverssl, clientssl)
1390             || !TEST_int_eq(idx * 2, new_called))
1391         goto end;
1392
1393     SSL_shutdown(clientssl);
1394     SSL_shutdown(serverssl);
1395     SSL_free(serverssl);
1396     SSL_free(clientssl);
1397     serverssl = clientssl = NULL;
1398
1399     /* Stop caching sessions - just count them */
1400     do_cache = 0;
1401
1402     /*
1403      * Check we can resume with all the tickets we created. This time around the
1404      * resumptions should all be successful.
1405      */
1406     if (!check_resumption(idx, sctx, cctx, 1))
1407         goto end;
1408
1409     testresult = 1;
1410
1411  end:
1412     SSL_free(serverssl);
1413     SSL_free(clientssl);
1414     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
1415         SSL_SESSION_free(sesscache[j]);
1416         sesscache[j] = NULL;
1417     }
1418     SSL_CTX_free(sctx);
1419     SSL_CTX_free(cctx);
1420
1421     return testresult;
1422 }
1423
1424 static int test_stateless_tickets(int idx)
1425 {
1426     return test_tickets(0, idx);
1427 }
1428
1429 static int test_stateful_tickets(int idx)
1430 {
1431     return test_tickets(1, idx);
1432 }
1433 #endif
1434
1435 #define USE_NULL            0
1436 #define USE_BIO_1           1
1437 #define USE_BIO_2           2
1438 #define USE_DEFAULT         3
1439
1440 #define CONNTYPE_CONNECTION_SUCCESS  0
1441 #define CONNTYPE_CONNECTION_FAIL     1
1442 #define CONNTYPE_NO_CONNECTION       2
1443
1444 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
1445 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
1446 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
1447 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
1448 #else
1449 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
1450 #endif
1451
1452 #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
1453                                 + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
1454                                 + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
1455
1456 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
1457 {
1458     switch (type) {
1459     case USE_NULL:
1460         *res = NULL;
1461         break;
1462     case USE_BIO_1:
1463         *res = bio1;
1464         break;
1465     case USE_BIO_2:
1466         *res = bio2;
1467         break;
1468     }
1469 }
1470
1471
1472 /*
1473  * Tests calls to SSL_set_bio() under various conditions.
1474  *
1475  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
1476  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
1477  * then do more tests where we create a successful connection first using our
1478  * standard connection setup functions, and then call SSL_set_bio() with
1479  * various combinations of valid BIOs or NULL. We then repeat these tests
1480  * following a failed connection. In this last case we are looking to check that
1481  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
1482  */
1483 static int test_ssl_set_bio(int idx)
1484 {
1485     SSL_CTX *sctx = NULL, *cctx = NULL;
1486     BIO *bio1 = NULL;
1487     BIO *bio2 = NULL;
1488     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
1489     SSL *serverssl = NULL, *clientssl = NULL;
1490     int initrbio, initwbio, newrbio, newwbio, conntype;
1491     int testresult = 0;
1492
1493     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
1494         initrbio = idx % 3;
1495         idx /= 3;
1496         initwbio = idx % 3;
1497         idx /= 3;
1498         newrbio = idx % 3;
1499         idx /= 3;
1500         newwbio = idx % 3;
1501         conntype = CONNTYPE_NO_CONNECTION;
1502     } else {
1503         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
1504         initrbio = initwbio = USE_DEFAULT;
1505         newrbio = idx % 2;
1506         idx /= 2;
1507         newwbio = idx % 2;
1508         idx /= 2;
1509         conntype = idx % 2;
1510     }
1511
1512     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1513                                        TLS1_VERSION, TLS_MAX_VERSION,
1514                                        &sctx, &cctx, cert, privkey)))
1515         goto end;
1516
1517     if (conntype == CONNTYPE_CONNECTION_FAIL) {
1518         /*
1519          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
1520          * because we reduced the number of tests in the definition of
1521          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
1522          * mismatched protocol versions we will force a connection failure.
1523          */
1524         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
1525         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1526     }
1527
1528     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1529                                       NULL, NULL)))
1530         goto end;
1531
1532     if (initrbio == USE_BIO_1
1533             || initwbio == USE_BIO_1
1534             || newrbio == USE_BIO_1
1535             || newwbio == USE_BIO_1) {
1536         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
1537             goto end;
1538     }
1539
1540     if (initrbio == USE_BIO_2
1541             || initwbio == USE_BIO_2
1542             || newrbio == USE_BIO_2
1543             || newwbio == USE_BIO_2) {
1544         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
1545             goto end;
1546     }
1547
1548     if (initrbio != USE_DEFAULT) {
1549         setupbio(&irbio, bio1, bio2, initrbio);
1550         setupbio(&iwbio, bio1, bio2, initwbio);
1551         SSL_set_bio(clientssl, irbio, iwbio);
1552
1553         /*
1554          * We want to maintain our own refs to these BIO, so do an up ref for
1555          * each BIO that will have ownership transferred in the SSL_set_bio()
1556          * call
1557          */
1558         if (irbio != NULL)
1559             BIO_up_ref(irbio);
1560         if (iwbio != NULL && iwbio != irbio)
1561             BIO_up_ref(iwbio);
1562     }
1563
1564     if (conntype != CONNTYPE_NO_CONNECTION
1565             && !TEST_true(create_ssl_connection(serverssl, clientssl,
1566                                                 SSL_ERROR_NONE)
1567                           == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
1568         goto end;
1569
1570     setupbio(&nrbio, bio1, bio2, newrbio);
1571     setupbio(&nwbio, bio1, bio2, newwbio);
1572
1573     /*
1574      * We will (maybe) transfer ownership again so do more up refs.
1575      * SSL_set_bio() has some really complicated ownership rules where BIOs have
1576      * already been set!
1577      */
1578     if (nrbio != NULL
1579             && nrbio != irbio
1580             && (nwbio != iwbio || nrbio != nwbio))
1581         BIO_up_ref(nrbio);
1582     if (nwbio != NULL
1583             && nwbio != nrbio
1584             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
1585         BIO_up_ref(nwbio);
1586
1587     SSL_set_bio(clientssl, nrbio, nwbio);
1588
1589     testresult = 1;
1590
1591  end:
1592     BIO_free(bio1);
1593     BIO_free(bio2);
1594
1595     /*
1596      * This test is checking that the ref counting for SSL_set_bio is correct.
1597      * If we get here and we did too many frees then we will fail in the above
1598      * functions. If we haven't done enough then this will only be detected in
1599      * a crypto-mdebug build
1600      */
1601     SSL_free(serverssl);
1602     SSL_free(clientssl);
1603     SSL_CTX_free(sctx);
1604     SSL_CTX_free(cctx);
1605     return testresult;
1606 }
1607
1608 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
1609
1610 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
1611 {
1612     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
1613     SSL_CTX *ctx;
1614     SSL *ssl = NULL;
1615     int testresult = 0;
1616
1617     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
1618             || !TEST_ptr(ssl = SSL_new(ctx))
1619             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
1620             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
1621         goto end;
1622
1623     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
1624
1625     /*
1626      * If anything goes wrong here then we could leak memory, so this will
1627      * be caught in a crypto-mdebug build
1628      */
1629     BIO_push(sslbio, membio1);
1630
1631     /* Verify changing the rbio/wbio directly does not cause leaks */
1632     if (change_bio != NO_BIO_CHANGE) {
1633         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem())))
1634             goto end;
1635         if (change_bio == CHANGE_RBIO)
1636             SSL_set0_rbio(ssl, membio2);
1637         else
1638             SSL_set0_wbio(ssl, membio2);
1639     }
1640     ssl = NULL;
1641
1642     if (pop_ssl)
1643         BIO_pop(sslbio);
1644     else
1645         BIO_pop(membio1);
1646
1647     testresult = 1;
1648  end:
1649     BIO_free(membio1);
1650     BIO_free(sslbio);
1651     SSL_free(ssl);
1652     SSL_CTX_free(ctx);
1653
1654     return testresult;
1655 }
1656
1657 static int test_ssl_bio_pop_next_bio(void)
1658 {
1659     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
1660 }
1661
1662 static int test_ssl_bio_pop_ssl_bio(void)
1663 {
1664     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
1665 }
1666
1667 static int test_ssl_bio_change_rbio(void)
1668 {
1669     return execute_test_ssl_bio(0, CHANGE_RBIO);
1670 }
1671
1672 static int test_ssl_bio_change_wbio(void)
1673 {
1674     return execute_test_ssl_bio(0, CHANGE_WBIO);
1675 }
1676
1677 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
1678 typedef struct {
1679     /* The list of sig algs */
1680     const int *list;
1681     /* The length of the list */
1682     size_t listlen;
1683     /* A sigalgs list in string format */
1684     const char *liststr;
1685     /* Whether setting the list should succeed */
1686     int valid;
1687     /* Whether creating a connection with the list should succeed */
1688     int connsuccess;
1689 } sigalgs_list;
1690
1691 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
1692 # ifndef OPENSSL_NO_EC
1693 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
1694 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
1695 # endif
1696 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
1697 static const int invalidlist2[] = {NID_sha256, NID_undef};
1698 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
1699 static const int invalidlist4[] = {NID_sha256};
1700 static const sigalgs_list testsigalgs[] = {
1701     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
1702 # ifndef OPENSSL_NO_EC
1703     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
1704     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
1705 # endif
1706     {NULL, 0, "RSA+SHA256", 1, 1},
1707 # ifndef OPENSSL_NO_EC
1708     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
1709     {NULL, 0, "ECDSA+SHA512", 1, 0},
1710 # endif
1711     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
1712     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
1713     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
1714     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
1715     {NULL, 0, "RSA", 0, 0},
1716     {NULL, 0, "SHA256", 0, 0},
1717     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
1718     {NULL, 0, "Invalid", 0, 0}
1719 };
1720
1721 static int test_set_sigalgs(int idx)
1722 {
1723     SSL_CTX *cctx = NULL, *sctx = NULL;
1724     SSL *clientssl = NULL, *serverssl = NULL;
1725     int testresult = 0;
1726     const sigalgs_list *curr;
1727     int testctx;
1728
1729     /* Should never happen */
1730     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
1731         return 0;
1732
1733     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
1734     curr = testctx ? &testsigalgs[idx]
1735                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
1736
1737     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1738                                        TLS1_VERSION, TLS_MAX_VERSION,
1739                                        &sctx, &cctx, cert, privkey)))
1740         return 0;
1741
1742     /*
1743      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
1744      * for TLSv1.2 for now until we add a new API.
1745      */
1746     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1747
1748     if (testctx) {
1749         int ret;
1750
1751         if (curr->list != NULL)
1752             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
1753         else
1754             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
1755
1756         if (!ret) {
1757             if (curr->valid)
1758                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
1759             else
1760                 testresult = 1;
1761             goto end;
1762         }
1763         if (!curr->valid) {
1764             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
1765             goto end;
1766         }
1767     }
1768
1769     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1770                                       &clientssl, NULL, NULL)))
1771         goto end;
1772
1773     if (!testctx) {
1774         int ret;
1775
1776         if (curr->list != NULL)
1777             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
1778         else
1779             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
1780         if (!ret) {
1781             if (curr->valid)
1782                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
1783             else
1784                 testresult = 1;
1785             goto end;
1786         }
1787         if (!curr->valid)
1788             goto end;
1789     }
1790
1791     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
1792                                            SSL_ERROR_NONE),
1793                 curr->connsuccess))
1794         goto end;
1795
1796     testresult = 1;
1797
1798  end:
1799     SSL_free(serverssl);
1800     SSL_free(clientssl);
1801     SSL_CTX_free(sctx);
1802     SSL_CTX_free(cctx);
1803
1804     return testresult;
1805 }
1806 #endif
1807
1808 #ifndef OPENSSL_NO_TLS1_3
1809
1810 static SSL_SESSION *clientpsk = NULL;
1811 static SSL_SESSION *serverpsk = NULL;
1812 static const char *pskid = "Identity";
1813 static const char *srvid;
1814
1815 static int use_session_cb_cnt = 0;
1816 static int find_session_cb_cnt = 0;
1817 static int psk_client_cb_cnt = 0;
1818 static int psk_server_cb_cnt = 0;
1819
1820 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
1821                           size_t *idlen, SSL_SESSION **sess)
1822 {
1823     switch (++use_session_cb_cnt) {
1824     case 1:
1825         /* The first call should always have a NULL md */
1826         if (md != NULL)
1827             return 0;
1828         break;
1829
1830     case 2:
1831         /* The second call should always have an md */
1832         if (md == NULL)
1833             return 0;
1834         break;
1835
1836     default:
1837         /* We should only be called a maximum of twice */
1838         return 0;
1839     }
1840
1841     if (clientpsk != NULL)
1842         SSL_SESSION_up_ref(clientpsk);
1843
1844     *sess = clientpsk;
1845     *id = (const unsigned char *)pskid;
1846     *idlen = strlen(pskid);
1847
1848     return 1;
1849 }
1850
1851 #ifndef OPENSSL_NO_PSK
1852 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
1853                                   unsigned int max_id_len,
1854                                   unsigned char *psk,
1855                                   unsigned int max_psk_len)
1856 {
1857     unsigned int psklen = 0;
1858
1859     psk_client_cb_cnt++;
1860
1861     if (strlen(pskid) + 1 > max_id_len)
1862         return 0;
1863
1864     /* We should only ever be called a maximum of twice per connection */
1865     if (psk_client_cb_cnt > 2)
1866         return 0;
1867
1868     if (clientpsk == NULL)
1869         return 0;
1870
1871     /* We'll reuse the PSK we set up for TLSv1.3 */
1872     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
1873         return 0;
1874     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
1875     strncpy(id, pskid, max_id_len);
1876
1877     return psklen;
1878 }
1879 #endif /* OPENSSL_NO_PSK */
1880
1881 static int find_session_cb(SSL *ssl, const unsigned char *identity,
1882                            size_t identity_len, SSL_SESSION **sess)
1883 {
1884     find_session_cb_cnt++;
1885
1886     /* We should only ever be called a maximum of twice per connection */
1887     if (find_session_cb_cnt > 2)
1888         return 0;
1889
1890     if (serverpsk == NULL)
1891         return 0;
1892
1893     /* Identity should match that set by the client */
1894     if (strlen(srvid) != identity_len
1895             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
1896         /* No PSK found, continue but without a PSK */
1897         *sess = NULL;
1898         return 1;
1899     }
1900
1901     SSL_SESSION_up_ref(serverpsk);
1902     *sess = serverpsk;
1903
1904     return 1;
1905 }
1906
1907 #ifndef OPENSSL_NO_PSK
1908 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
1909                                   unsigned char *psk, unsigned int max_psk_len)
1910 {
1911     unsigned int psklen = 0;
1912
1913     psk_server_cb_cnt++;
1914
1915     /* We should only ever be called a maximum of twice per connection */
1916     if (find_session_cb_cnt > 2)
1917         return 0;
1918
1919     if (serverpsk == NULL)
1920         return 0;
1921
1922     /* Identity should match that set by the client */
1923     if (strcmp(srvid, identity) != 0) {
1924         return 0;
1925     }
1926
1927     /* We'll reuse the PSK we set up for TLSv1.3 */
1928     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
1929         return 0;
1930     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
1931
1932     return psklen;
1933 }
1934 #endif /* OPENSSL_NO_PSK */
1935
1936 #define MSG1    "Hello"
1937 #define MSG2    "World."
1938 #define MSG3    "This"
1939 #define MSG4    "is"
1940 #define MSG5    "a"
1941 #define MSG6    "test"
1942 #define MSG7    "message."
1943
1944 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
1945 #define TLS13_AES_128_GCM_SHA256_BYTES  ((const unsigned char *)"\x13\x01")
1946
1947 /*
1948  * Helper method to setup objects for early data test. Caller frees objects on
1949  * error.
1950  */
1951 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
1952                                 SSL **serverssl, SSL_SESSION **sess, int idx)
1953 {
1954     if (*sctx == NULL
1955             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1956                                               TLS_client_method(),
1957                                               TLS1_VERSION, TLS_MAX_VERSION,
1958                                               sctx, cctx, cert, privkey)))
1959         return 0;
1960
1961     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
1962         return 0;
1963
1964     if (idx == 1) {
1965         /* When idx == 1 we repeat the tests with read_ahead set */
1966         SSL_CTX_set_read_ahead(*cctx, 1);
1967         SSL_CTX_set_read_ahead(*sctx, 1);
1968     } else if (idx == 2) {
1969         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
1970         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
1971         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
1972         use_session_cb_cnt = 0;
1973         find_session_cb_cnt = 0;
1974         srvid = pskid;
1975     }
1976
1977     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
1978                                       NULL, NULL)))
1979         return 0;
1980
1981     /*
1982      * For one of the run throughs (doesn't matter which one), we'll try sending
1983      * some SNI data in the initial ClientHello. This will be ignored (because
1984      * there is no SNI cb set up by the server), so it should not impact
1985      * early_data.
1986      */
1987     if (idx == 1
1988             && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
1989         return 0;
1990
1991     if (idx == 2) {
1992         /* Create the PSK */
1993         const SSL_CIPHER *cipher = NULL;
1994         const unsigned char key[] = {
1995             0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
1996             0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
1997             0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
1998             0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
1999             0x2c, 0x2d, 0x2e, 0x2f
2000         };
2001
2002         cipher = SSL_CIPHER_find(*clientssl, TLS13_AES_256_GCM_SHA384_BYTES);
2003         clientpsk = SSL_SESSION_new();
2004         if (!TEST_ptr(clientpsk)
2005                 || !TEST_ptr(cipher)
2006                 || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
2007                                                           sizeof(key)))
2008                 || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
2009                 || !TEST_true(
2010                         SSL_SESSION_set_protocol_version(clientpsk,
2011                                                          TLS1_3_VERSION))
2012                    /*
2013                     * We just choose an arbitrary value for max_early_data which
2014                     * should be big enough for testing purposes.
2015                     */
2016                 || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
2017                                                              0x100))
2018                 || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
2019             SSL_SESSION_free(clientpsk);
2020             clientpsk = NULL;
2021             return 0;
2022         }
2023         serverpsk = clientpsk;
2024
2025         if (sess != NULL) {
2026             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
2027                 SSL_SESSION_free(clientpsk);
2028                 SSL_SESSION_free(serverpsk);
2029                 clientpsk = serverpsk = NULL;
2030                 return 0;
2031             }
2032             *sess = clientpsk;
2033         }
2034         return 1;
2035     }
2036
2037     if (sess == NULL)
2038         return 1;
2039
2040     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
2041                                          SSL_ERROR_NONE)))
2042         return 0;
2043
2044     *sess = SSL_get1_session(*clientssl);
2045     SSL_shutdown(*clientssl);
2046     SSL_shutdown(*serverssl);
2047     SSL_free(*serverssl);
2048     SSL_free(*clientssl);
2049     *serverssl = *clientssl = NULL;
2050
2051     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
2052                                       clientssl, NULL, NULL))
2053             || !TEST_true(SSL_set_session(*clientssl, *sess)))
2054         return 0;
2055
2056     return 1;
2057 }
2058
2059 static int test_early_data_read_write(int idx)
2060 {
2061     SSL_CTX *cctx = NULL, *sctx = NULL;
2062     SSL *clientssl = NULL, *serverssl = NULL;
2063     int testresult = 0;
2064     SSL_SESSION *sess = NULL;
2065     unsigned char buf[20], data[1024];
2066     size_t readbytes, written, eoedlen, rawread, rawwritten;
2067     BIO *rbio;
2068
2069     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2070                                         &serverssl, &sess, idx)))
2071         goto end;
2072
2073     /* Write and read some early data */
2074     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2075                                         &written))
2076             || !TEST_size_t_eq(written, strlen(MSG1))
2077             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
2078                                                 sizeof(buf), &readbytes),
2079                             SSL_READ_EARLY_DATA_SUCCESS)
2080             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
2081             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2082                             SSL_EARLY_DATA_ACCEPTED))
2083         goto end;
2084
2085     /*
2086      * Server should be able to write data, and client should be able to
2087      * read it.
2088      */
2089     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
2090                                         &written))
2091             || !TEST_size_t_eq(written, strlen(MSG2))
2092             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2093             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2094         goto end;
2095
2096     /* Even after reading normal data, client should be able write early data */
2097     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
2098                                         &written))
2099             || !TEST_size_t_eq(written, strlen(MSG3)))
2100         goto end;
2101
2102     /* Server should still be able read early data after writing data */
2103     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2104                                          &readbytes),
2105                      SSL_READ_EARLY_DATA_SUCCESS)
2106             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
2107         goto end;
2108
2109     /* Write more data from server and read it from client */
2110     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
2111                                         &written))
2112             || !TEST_size_t_eq(written, strlen(MSG4))
2113             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2114             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
2115         goto end;
2116
2117     /*
2118      * If client writes normal data it should mean writing early data is no
2119      * longer possible.
2120      */
2121     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
2122             || !TEST_size_t_eq(written, strlen(MSG5))
2123             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2124                             SSL_EARLY_DATA_ACCEPTED))
2125         goto end;
2126
2127     /*
2128      * At this point the client has written EndOfEarlyData, ClientFinished and
2129      * normal (fully protected) data. We are going to cause a delay between the
2130      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
2131      * in the read BIO, and then just put back the EndOfEarlyData message.
2132      */
2133     rbio = SSL_get_rbio(serverssl);
2134     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
2135             || !TEST_size_t_lt(rawread, sizeof(data))
2136             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
2137         goto end;
2138
2139     /* Record length is in the 4th and 5th bytes of the record header */
2140     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
2141     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
2142             || !TEST_size_t_eq(rawwritten, eoedlen))
2143         goto end;
2144
2145     /* Server should be told that there is no more early data */
2146     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2147                                          &readbytes),
2148                      SSL_READ_EARLY_DATA_FINISH)
2149             || !TEST_size_t_eq(readbytes, 0))
2150         goto end;
2151
2152     /*
2153      * Server has not finished init yet, so should still be able to write early
2154      * data.
2155      */
2156     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
2157                                         &written))
2158             || !TEST_size_t_eq(written, strlen(MSG6)))
2159         goto end;
2160
2161     /* Push the ClientFinished and the normal data back into the server rbio */
2162     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
2163                                 &rawwritten))
2164             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
2165         goto end;
2166
2167     /* Server should be able to read normal data */
2168     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2169             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
2170         goto end;
2171
2172     /* Client and server should not be able to write/read early data now */
2173     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
2174                                          &written)))
2175         goto end;
2176     ERR_clear_error();
2177     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2178                                          &readbytes),
2179                      SSL_READ_EARLY_DATA_ERROR))
2180         goto end;
2181     ERR_clear_error();
2182
2183     /* Client should be able to read the data sent by the server */
2184     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2185             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
2186         goto end;
2187
2188     /*
2189      * Make sure we process the two NewSessionTickets. These arrive
2190      * post-handshake. We attempt reads which we do not expect to return any
2191      * data.
2192      */
2193     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2194             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
2195                            &readbytes)))
2196         goto end;
2197
2198     /* Server should be able to write normal data */
2199     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
2200             || !TEST_size_t_eq(written, strlen(MSG7))
2201             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2202             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
2203         goto end;
2204
2205     SSL_SESSION_free(sess);
2206     sess = SSL_get1_session(clientssl);
2207     use_session_cb_cnt = 0;
2208     find_session_cb_cnt = 0;
2209
2210     SSL_shutdown(clientssl);
2211     SSL_shutdown(serverssl);
2212     SSL_free(serverssl);
2213     SSL_free(clientssl);
2214     serverssl = clientssl = NULL;
2215     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2216                                       &clientssl, NULL, NULL))
2217             || !TEST_true(SSL_set_session(clientssl, sess)))
2218         goto end;
2219
2220     /* Write and read some early data */
2221     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2222                                         &written))
2223             || !TEST_size_t_eq(written, strlen(MSG1))
2224             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2225                                                 &readbytes),
2226                             SSL_READ_EARLY_DATA_SUCCESS)
2227             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
2228         goto end;
2229
2230     if (!TEST_int_gt(SSL_connect(clientssl), 0)
2231             || !TEST_int_gt(SSL_accept(serverssl), 0))
2232         goto end;
2233
2234     /* Client and server should not be able to write/read early data now */
2235     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
2236                                          &written)))
2237         goto end;
2238     ERR_clear_error();
2239     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2240                                          &readbytes),
2241                      SSL_READ_EARLY_DATA_ERROR))
2242         goto end;
2243     ERR_clear_error();
2244
2245     /* Client and server should be able to write/read normal data */
2246     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
2247             || !TEST_size_t_eq(written, strlen(MSG5))
2248             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2249             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
2250         goto end;
2251
2252     testresult = 1;
2253
2254  end:
2255     SSL_SESSION_free(sess);
2256     SSL_SESSION_free(clientpsk);
2257     SSL_SESSION_free(serverpsk);
2258     clientpsk = serverpsk = NULL;
2259     SSL_free(serverssl);
2260     SSL_free(clientssl);
2261     SSL_CTX_free(sctx);
2262     SSL_CTX_free(cctx);
2263     return testresult;
2264 }
2265
2266 static int allow_ed_cb_called = 0;
2267
2268 static int allow_early_data_cb(SSL *s, void *arg)
2269 {
2270     int *usecb = (int *)arg;
2271
2272     allow_ed_cb_called++;
2273
2274     if (*usecb == 1)
2275         return 0;
2276
2277     return 1;
2278 }
2279
2280 /*
2281  * idx == 0: Standard early_data setup
2282  * idx == 1: early_data setup using read_ahead
2283  * usecb == 0: Don't use a custom early data callback
2284  * usecb == 1: Use a custom early data callback and reject the early data
2285  * usecb == 2: Use a custom early data callback and accept the early data
2286  * confopt == 0: Configure anti-replay directly
2287  * confopt == 1: Configure anti-replay using SSL_CONF
2288  */
2289 static int test_early_data_replay_int(int idx, int usecb, int confopt)
2290 {
2291     SSL_CTX *cctx = NULL, *sctx = NULL;
2292     SSL *clientssl = NULL, *serverssl = NULL;
2293     int testresult = 0;
2294     SSL_SESSION *sess = NULL;
2295     size_t readbytes, written;
2296     unsigned char buf[20];
2297
2298     allow_ed_cb_called = 0;
2299
2300     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2301                                        TLS1_VERSION, TLS_MAX_VERSION, &sctx,
2302                                        &cctx, cert, privkey)))
2303         return 0;
2304
2305     if (usecb > 0) {
2306         if (confopt == 0) {
2307             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
2308         } else {
2309             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
2310
2311             if (!TEST_ptr(confctx))
2312                 goto end;
2313             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
2314                                             | SSL_CONF_FLAG_SERVER);
2315             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
2316             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
2317                              2)) {
2318                 SSL_CONF_CTX_free(confctx);
2319                 goto end;
2320             }
2321             SSL_CONF_CTX_free(confctx);
2322         }
2323         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
2324     }
2325
2326     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2327                                         &serverssl, &sess, idx)))
2328         goto end;
2329
2330     /*
2331      * The server is configured to accept early data. Create a connection to
2332      * "use up" the ticket
2333      */
2334     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2335             || !TEST_true(SSL_session_reused(clientssl)))
2336         goto end;
2337
2338     SSL_shutdown(clientssl);
2339     SSL_shutdown(serverssl);
2340     SSL_free(serverssl);
2341     SSL_free(clientssl);
2342     serverssl = clientssl = NULL;
2343
2344     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2345                                       &clientssl, NULL, NULL))
2346             || !TEST_true(SSL_set_session(clientssl, sess)))
2347         goto end;
2348
2349     /* Write and read some early data */
2350     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2351                                         &written))
2352             || !TEST_size_t_eq(written, strlen(MSG1)))
2353         goto end;
2354
2355     if (usecb <= 1) {
2356         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2357                                              &readbytes),
2358                          SSL_READ_EARLY_DATA_FINISH)
2359                    /*
2360                     * The ticket was reused, so the we should have rejected the
2361                     * early data
2362                     */
2363                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2364                                 SSL_EARLY_DATA_REJECTED))
2365             goto end;
2366     } else {
2367         /* In this case the callback decides to accept the early data */
2368         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2369                                              &readbytes),
2370                          SSL_READ_EARLY_DATA_SUCCESS)
2371                 || !TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
2372                    /*
2373                     * Server will have sent its flight so client can now send
2374                     * end of early data and complete its half of the handshake
2375                     */
2376                 || !TEST_int_gt(SSL_connect(clientssl), 0)
2377                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2378                                              &readbytes),
2379                                 SSL_READ_EARLY_DATA_FINISH)
2380                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2381                                 SSL_EARLY_DATA_ACCEPTED))
2382             goto end;
2383     }
2384
2385     /* Complete the connection */
2386     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2387             || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
2388             || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
2389         goto end;
2390
2391     testresult = 1;
2392
2393  end:
2394     SSL_SESSION_free(sess);
2395     SSL_SESSION_free(clientpsk);
2396     SSL_SESSION_free(serverpsk);
2397     clientpsk = serverpsk = NULL;
2398     SSL_free(serverssl);
2399     SSL_free(clientssl);
2400     SSL_CTX_free(sctx);
2401     SSL_CTX_free(cctx);
2402     return testresult;
2403 }
2404
2405 static int test_early_data_replay(int idx)
2406 {
2407     int ret = 1, usecb, confopt;
2408
2409     for (usecb = 0; usecb < 3; usecb++) {
2410         for (confopt = 0; confopt < 2; confopt++)
2411             ret &= test_early_data_replay_int(idx, usecb, confopt);
2412     }
2413
2414     return ret;
2415 }
2416
2417 /*
2418  * Helper function to test that a server attempting to read early data can
2419  * handle a connection from a client where the early data should be skipped.
2420  * testtype: 0 == No HRR
2421  * testtype: 1 == HRR
2422  * testtype: 2 == recv_max_early_data set to 0
2423  */
2424 static int early_data_skip_helper(int testtype, int idx)
2425 {
2426     SSL_CTX *cctx = NULL, *sctx = NULL;
2427     SSL *clientssl = NULL, *serverssl = NULL;
2428     int testresult = 0;
2429     SSL_SESSION *sess = NULL;
2430     unsigned char buf[20];
2431     size_t readbytes, written;
2432
2433     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2434                                         &serverssl, &sess, idx)))
2435         goto end;
2436
2437     if (testtype == 1) {
2438         /* Force an HRR to occur */
2439         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2440             goto end;
2441     } else if (idx == 2) {
2442         /*
2443          * We force early_data rejection by ensuring the PSK identity is
2444          * unrecognised
2445          */
2446         srvid = "Dummy Identity";
2447     } else {
2448         /*
2449          * Deliberately corrupt the creation time. We take 20 seconds off the
2450          * time. It could be any value as long as it is not within tolerance.
2451          * This should mean the ticket is rejected.
2452          */
2453         if (!TEST_true(SSL_SESSION_set_time(sess, (long)(time(NULL) - 20))))
2454             goto end;
2455     }
2456
2457     if (testtype == 2
2458             && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
2459         goto end;
2460
2461     /* Write some early data */
2462     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2463                                         &written))
2464             || !TEST_size_t_eq(written, strlen(MSG1)))
2465         goto end;
2466
2467     /* Server should reject the early data */
2468     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2469                                          &readbytes),
2470                      SSL_READ_EARLY_DATA_FINISH)
2471             || !TEST_size_t_eq(readbytes, 0)
2472             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2473                             SSL_EARLY_DATA_REJECTED))
2474         goto end;
2475
2476     if (testtype == 1) {
2477         /*
2478          * Finish off the handshake. We perform the same writes and reads as
2479          * further down but we expect them to fail due to the incomplete
2480          * handshake.
2481          */
2482         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2483                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
2484                                &readbytes)))
2485             goto end;
2486     } else if (testtype == 2) {
2487         /*
2488          * This client has sent more early_data than we are willing to skip so
2489          * the connection should abort.
2490          */
2491         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2492                 || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
2493             goto end;
2494
2495         /* Connection has failed - nothing more to do */
2496         testresult = 1;
2497         goto end;
2498     }
2499
2500     /*
2501      * Should be able to send normal data despite rejection of early data. The
2502      * early_data should be skipped.
2503      */
2504     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2505             || !TEST_size_t_eq(written, strlen(MSG2))
2506             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2507                             SSL_EARLY_DATA_REJECTED)
2508             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2509             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2510         goto end;
2511
2512     testresult = 1;
2513
2514  end:
2515     SSL_SESSION_free(clientpsk);
2516     SSL_SESSION_free(serverpsk);
2517     clientpsk = serverpsk = NULL;
2518     SSL_SESSION_free(sess);
2519     SSL_free(serverssl);
2520     SSL_free(clientssl);
2521     SSL_CTX_free(sctx);
2522     SSL_CTX_free(cctx);
2523     return testresult;
2524 }
2525
2526 /*
2527  * Test that a server attempting to read early data can handle a connection
2528  * from a client where the early data is not acceptable.
2529  */
2530 static int test_early_data_skip(int idx)
2531 {
2532     return early_data_skip_helper(0, idx);
2533 }
2534
2535 /*
2536  * Test that a server attempting to read early data can handle a connection
2537  * from a client where an HRR occurs.
2538  */
2539 static int test_early_data_skip_hrr(int idx)
2540 {
2541     return early_data_skip_helper(1, idx);
2542 }
2543
2544 /*
2545  * Test that a server attempting to read early data will abort if it tries to
2546  * skip over too much.
2547  */
2548 static int test_early_data_skip_abort(int idx)
2549 {
2550     return early_data_skip_helper(2, idx);
2551 }
2552
2553 /*
2554  * Test that a server attempting to read early data can handle a connection
2555  * from a client that doesn't send any.
2556  */
2557 static int test_early_data_not_sent(int idx)
2558 {
2559     SSL_CTX *cctx = NULL, *sctx = NULL;
2560     SSL *clientssl = NULL, *serverssl = NULL;
2561     int testresult = 0;
2562     SSL_SESSION *sess = NULL;
2563     unsigned char buf[20];
2564     size_t readbytes, written;
2565
2566     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2567                                         &serverssl, &sess, idx)))
2568         goto end;
2569
2570     /* Write some data - should block due to handshake with server */
2571     SSL_set_connect_state(clientssl);
2572     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
2573         goto end;
2574
2575     /* Server should detect that early data has not been sent */
2576     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2577                                          &readbytes),
2578                      SSL_READ_EARLY_DATA_FINISH)
2579             || !TEST_size_t_eq(readbytes, 0)
2580             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2581                             SSL_EARLY_DATA_NOT_SENT)
2582             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2583                             SSL_EARLY_DATA_NOT_SENT))
2584         goto end;
2585
2586     /* Continue writing the message we started earlier */
2587     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2588             || !TEST_size_t_eq(written, strlen(MSG1))
2589             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2590             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
2591             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
2592             || !TEST_size_t_eq(written, strlen(MSG2)))
2593         goto end;
2594
2595     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2596             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2597         goto end;
2598
2599     testresult = 1;
2600
2601  end:
2602     SSL_SESSION_free(sess);
2603     SSL_SESSION_free(clientpsk);
2604     SSL_SESSION_free(serverpsk);
2605     clientpsk = serverpsk = NULL;
2606     SSL_free(serverssl);
2607     SSL_free(clientssl);
2608     SSL_CTX_free(sctx);
2609     SSL_CTX_free(cctx);
2610     return testresult;
2611 }
2612
2613 static int hostname_cb(SSL *s, int *al, void *arg)
2614 {
2615     const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2616
2617     if (hostname != NULL && strcmp(hostname, "goodhost") == 0)
2618         return  SSL_TLSEXT_ERR_OK;
2619
2620     return SSL_TLSEXT_ERR_NOACK;
2621 }
2622
2623 static const char *servalpn;
2624
2625 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
2626                           unsigned char *outlen, const unsigned char *in,
2627                           unsigned int inlen, void *arg)
2628 {
2629     unsigned int protlen = 0;
2630     const unsigned char *prot;
2631
2632     for (prot = in; prot < in + inlen; prot += protlen) {
2633         protlen = *prot++;
2634         if (in + inlen < prot + protlen)
2635             return SSL_TLSEXT_ERR_NOACK;
2636
2637         if (protlen == strlen(servalpn)
2638                 && memcmp(prot, servalpn, protlen) == 0) {
2639             *out = prot;
2640             *outlen = protlen;
2641             return SSL_TLSEXT_ERR_OK;
2642         }
2643     }
2644
2645     return SSL_TLSEXT_ERR_NOACK;
2646 }
2647
2648 /* Test that a PSK can be used to send early_data */
2649 static int test_early_data_psk(int idx)
2650 {
2651     SSL_CTX *cctx = NULL, *sctx = NULL;
2652     SSL *clientssl = NULL, *serverssl = NULL;
2653     int testresult = 0;
2654     SSL_SESSION *sess = NULL;
2655     unsigned char alpnlist[] = {
2656         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
2657         'l', 'p', 'n'
2658     };
2659 #define GOODALPNLEN     9
2660 #define BADALPNLEN      8
2661 #define GOODALPN        (alpnlist)
2662 #define BADALPN         (alpnlist + GOODALPNLEN)
2663     int err = 0;
2664     unsigned char buf[20];
2665     size_t readbytes, written;
2666     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
2667     int edstatus = SSL_EARLY_DATA_ACCEPTED;
2668
2669     /* We always set this up with a final parameter of "2" for PSK */
2670     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2671                                         &serverssl, &sess, 2)))
2672         goto end;
2673
2674     servalpn = "goodalpn";
2675
2676     /*
2677      * Note: There is no test for inconsistent SNI with late client detection.
2678      * This is because servers do not acknowledge SNI even if they are using
2679      * it in a resumption handshake - so it is not actually possible for a
2680      * client to detect a problem.
2681      */
2682     switch (idx) {
2683     case 0:
2684         /* Set inconsistent SNI (early client detection) */
2685         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
2686         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2687                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
2688             goto end;
2689         break;
2690
2691     case 1:
2692         /* Set inconsistent ALPN (early client detection) */
2693         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
2694         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
2695         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
2696                                                       GOODALPNLEN))
2697                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
2698                                                    BADALPNLEN)))
2699             goto end;
2700         break;
2701
2702     case 2:
2703         /*
2704          * Set invalid protocol version. Technically this affects PSKs without
2705          * early_data too, but we test it here because it is similar to the
2706          * SNI/ALPN consistency tests.
2707          */
2708         err = SSL_R_BAD_PSK;
2709         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
2710             goto end;
2711         break;
2712
2713     case 3:
2714         /*
2715          * Set inconsistent SNI (server detected). In this case the connection
2716          * will succeed but reject early_data.
2717          */
2718         SSL_SESSION_free(serverpsk);
2719         serverpsk = SSL_SESSION_dup(clientpsk);
2720         if (!TEST_ptr(serverpsk)
2721                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
2722             goto end;
2723         edstatus = SSL_EARLY_DATA_REJECTED;
2724         readearlyres = SSL_READ_EARLY_DATA_FINISH;
2725         /* Fall through */
2726     case 4:
2727         /* Set consistent SNI */
2728         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2729                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
2730                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
2731                                 hostname_cb)))
2732             goto end;
2733         break;
2734
2735     case 5:
2736         /*
2737          * Set inconsistent ALPN (server detected). In this case the connection
2738          * will succeed but reject early_data.
2739          */
2740         servalpn = "badalpn";
2741         edstatus = SSL_EARLY_DATA_REJECTED;
2742         readearlyres = SSL_READ_EARLY_DATA_FINISH;
2743         /* Fall through */
2744     case 6:
2745         /*
2746          * Set consistent ALPN.
2747          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
2748          * accepts a list of protos (each one length prefixed).
2749          * SSL_set1_alpn_selected accepts a single protocol (not length
2750          * prefixed)
2751          */
2752         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
2753                                                       GOODALPNLEN - 1))
2754                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
2755                                                    GOODALPNLEN)))
2756             goto end;
2757
2758         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
2759         break;
2760
2761     case 7:
2762         /* Set inconsistent ALPN (late client detection) */
2763         SSL_SESSION_free(serverpsk);
2764         serverpsk = SSL_SESSION_dup(clientpsk);
2765         if (!TEST_ptr(serverpsk)
2766                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
2767                                                              BADALPN + 1,
2768                                                              BADALPNLEN - 1))
2769                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
2770                                                              GOODALPN + 1,
2771                                                              GOODALPNLEN - 1))
2772                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
2773                                                    sizeof(alpnlist))))
2774             goto end;
2775         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
2776         edstatus = SSL_EARLY_DATA_ACCEPTED;
2777         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
2778         /* SSL_connect() call should fail */
2779         connectres = -1;
2780         break;
2781
2782     default:
2783         TEST_error("Bad test index");
2784         goto end;
2785     }
2786
2787     SSL_set_connect_state(clientssl);
2788     if (err != 0) {
2789         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2790                                             &written))
2791                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
2792                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
2793             goto end;
2794     } else {
2795         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2796                                             &written)))
2797             goto end;
2798
2799         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2800                                              &readbytes), readearlyres)
2801                 || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
2802                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
2803                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
2804                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
2805             goto end;
2806     }
2807
2808     testresult = 1;
2809
2810  end:
2811     SSL_SESSION_free(sess);
2812     SSL_SESSION_free(clientpsk);
2813     SSL_SESSION_free(serverpsk);
2814     clientpsk = serverpsk = NULL;
2815     SSL_free(serverssl);
2816     SSL_free(clientssl);
2817     SSL_CTX_free(sctx);
2818     SSL_CTX_free(cctx);
2819     return testresult;
2820 }
2821
2822 /*
2823  * Test that a server that doesn't try to read early data can handle a
2824  * client sending some.
2825  */
2826 static int test_early_data_not_expected(int idx)
2827 {
2828     SSL_CTX *cctx = NULL, *sctx = NULL;
2829     SSL *clientssl = NULL, *serverssl = NULL;
2830     int testresult = 0;
2831     SSL_SESSION *sess = NULL;
2832     unsigned char buf[20];
2833     size_t readbytes, written;
2834
2835     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2836                                         &serverssl, &sess, idx)))
2837         goto end;
2838
2839     /* Write some early data */
2840     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2841                                         &written)))
2842         goto end;
2843
2844     /*
2845      * Server should skip over early data and then block waiting for client to
2846      * continue handshake
2847      */
2848     if (!TEST_int_le(SSL_accept(serverssl), 0)
2849      || !TEST_int_gt(SSL_connect(clientssl), 0)
2850      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2851                      SSL_EARLY_DATA_REJECTED)
2852      || !TEST_int_gt(SSL_accept(serverssl), 0)
2853      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2854                      SSL_EARLY_DATA_REJECTED))
2855         goto end;
2856
2857     /* Send some normal data from client to server */
2858     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2859             || !TEST_size_t_eq(written, strlen(MSG2)))
2860         goto end;
2861
2862     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2863             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2864         goto end;
2865
2866     testresult = 1;
2867
2868  end:
2869     SSL_SESSION_free(sess);
2870     SSL_SESSION_free(clientpsk);
2871     SSL_SESSION_free(serverpsk);
2872     clientpsk = serverpsk = NULL;
2873     SSL_free(serverssl);
2874     SSL_free(clientssl);
2875     SSL_CTX_free(sctx);
2876     SSL_CTX_free(cctx);
2877     return testresult;
2878 }
2879
2880
2881 # ifndef OPENSSL_NO_TLS1_2
2882 /*
2883  * Test that a server attempting to read early data can handle a connection
2884  * from a TLSv1.2 client.
2885  */
2886 static int test_early_data_tls1_2(int idx)
2887 {
2888     SSL_CTX *cctx = NULL, *sctx = NULL;
2889     SSL *clientssl = NULL, *serverssl = NULL;
2890     int testresult = 0;
2891     unsigned char buf[20];
2892     size_t readbytes, written;
2893
2894     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2895                                         &serverssl, NULL, idx)))
2896         goto end;
2897
2898     /* Write some data - should block due to handshake with server */
2899     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
2900     SSL_set_connect_state(clientssl);
2901     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
2902         goto end;
2903
2904     /*
2905      * Server should do TLSv1.2 handshake. First it will block waiting for more
2906      * messages from client after ServerDone. Then SSL_read_early_data should
2907      * finish and detect that early data has not been sent
2908      */
2909     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2910                                          &readbytes),
2911                      SSL_READ_EARLY_DATA_ERROR))
2912         goto end;
2913
2914     /*
2915      * Continue writing the message we started earlier. Will still block waiting
2916      * for the CCS/Finished from server
2917      */
2918     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2919             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2920                                                 &readbytes),
2921                             SSL_READ_EARLY_DATA_FINISH)
2922             || !TEST_size_t_eq(readbytes, 0)
2923             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2924                             SSL_EARLY_DATA_NOT_SENT))
2925         goto end;
2926
2927     /* Continue writing the message we started earlier */
2928     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2929             || !TEST_size_t_eq(written, strlen(MSG1))
2930             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2931                             SSL_EARLY_DATA_NOT_SENT)
2932             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2933             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
2934             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
2935             || !TEST_size_t_eq(written, strlen(MSG2))
2936             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
2937             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2938         goto end;
2939
2940     testresult = 1;
2941
2942  end:
2943     SSL_SESSION_free(clientpsk);
2944     SSL_SESSION_free(serverpsk);
2945     clientpsk = serverpsk = NULL;
2946     SSL_free(serverssl);
2947     SSL_free(clientssl);
2948     SSL_CTX_free(sctx);
2949     SSL_CTX_free(cctx);
2950
2951     return testresult;
2952 }
2953 # endif /* OPENSSL_NO_TLS1_2 */
2954
2955 /*
2956  * Test configuring the TLSv1.3 ciphersuites
2957  *
2958  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
2959  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
2960  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
2961  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
2962  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
2963  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
2964  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
2965  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
2966  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
2967  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
2968  */
2969 static int test_set_ciphersuite(int idx)
2970 {
2971     SSL_CTX *cctx = NULL, *sctx = NULL;
2972     SSL *clientssl = NULL, *serverssl = NULL;
2973     int testresult = 0;
2974
2975     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2976                                        TLS1_VERSION, TLS_MAX_VERSION,
2977                                        &sctx, &cctx, cert, privkey))
2978             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
2979                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
2980         goto end;
2981
2982     if (idx >=4 && idx <= 7) {
2983         /* SSL_CTX explicit cipher list */
2984         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
2985             goto end;
2986     }
2987
2988     if (idx == 0 || idx == 4) {
2989         /* Default ciphersuite */
2990         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2991                                                 "TLS_AES_128_GCM_SHA256")))
2992             goto end;
2993     } else if (idx == 1 || idx == 5) {
2994         /* Non default ciphersuite */
2995         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2996                                                 "TLS_AES_128_CCM_SHA256")))
2997             goto end;
2998     }
2999
3000     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3001                                           &clientssl, NULL, NULL)))
3002         goto end;
3003
3004     if (idx == 8 || idx == 9) {
3005         /* SSL explicit cipher list */
3006         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
3007             goto end;
3008     }
3009
3010     if (idx == 2 || idx == 6 || idx == 8) {
3011         /* Default ciphersuite */
3012         if (!TEST_true(SSL_set_ciphersuites(clientssl,
3013                                             "TLS_AES_128_GCM_SHA256")))
3014             goto end;
3015     } else if (idx == 3 || idx == 7 || idx == 9) {
3016         /* Non default ciphersuite */
3017         if (!TEST_true(SSL_set_ciphersuites(clientssl,
3018                                             "TLS_AES_128_CCM_SHA256")))
3019             goto end;
3020     }
3021
3022     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
3023         goto end;
3024
3025     testresult = 1;
3026
3027  end:
3028     SSL_free(serverssl);
3029     SSL_free(clientssl);
3030     SSL_CTX_free(sctx);
3031     SSL_CTX_free(cctx);
3032
3033     return testresult;
3034 }
3035
3036 static int test_ciphersuite_change(void)
3037 {
3038     SSL_CTX *cctx = NULL, *sctx = NULL;
3039     SSL *clientssl = NULL, *serverssl = NULL;
3040     SSL_SESSION *clntsess = NULL;
3041     int testresult = 0;
3042     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
3043
3044     /* Create a session based on SHA-256 */
3045     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3046                                        TLS1_VERSION, TLS_MAX_VERSION,
3047                                        &sctx, &cctx, cert, privkey))
3048             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
3049                                                    "TLS_AES_128_GCM_SHA256"))
3050             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3051                                           &clientssl, NULL, NULL))
3052             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3053                                                 SSL_ERROR_NONE)))
3054         goto end;
3055
3056     clntsess = SSL_get1_session(clientssl);
3057     /* Save for later */
3058     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
3059     SSL_shutdown(clientssl);
3060     SSL_shutdown(serverssl);
3061     SSL_free(serverssl);
3062     SSL_free(clientssl);
3063     serverssl = clientssl = NULL;
3064
3065 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3066     /* Check we can resume a session with a different SHA-256 ciphersuite */
3067     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3068                                             "TLS_CHACHA20_POLY1305_SHA256"))
3069             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3070                                              NULL, NULL))
3071             || !TEST_true(SSL_set_session(clientssl, clntsess))
3072             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3073                                                 SSL_ERROR_NONE))
3074             || !TEST_true(SSL_session_reused(clientssl)))
3075         goto end;
3076
3077     SSL_SESSION_free(clntsess);
3078     clntsess = SSL_get1_session(clientssl);
3079     SSL_shutdown(clientssl);
3080     SSL_shutdown(serverssl);
3081     SSL_free(serverssl);
3082     SSL_free(clientssl);
3083     serverssl = clientssl = NULL;
3084 # endif
3085
3086     /*
3087      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
3088      * succeeds but does not resume.
3089      */
3090     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
3091             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3092                                              NULL, NULL))
3093             || !TEST_true(SSL_set_session(clientssl, clntsess))
3094             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3095                                                 SSL_ERROR_SSL))
3096             || !TEST_false(SSL_session_reused(clientssl)))
3097         goto end;
3098
3099     SSL_SESSION_free(clntsess);
3100     clntsess = NULL;
3101     SSL_shutdown(clientssl);
3102     SSL_shutdown(serverssl);
3103     SSL_free(serverssl);
3104     SSL_free(clientssl);
3105     serverssl = clientssl = NULL;
3106
3107     /* Create a session based on SHA384 */
3108     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
3109             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3110                                           &clientssl, NULL, NULL))
3111             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3112                                                 SSL_ERROR_NONE)))
3113         goto end;
3114
3115     clntsess = SSL_get1_session(clientssl);
3116     SSL_shutdown(clientssl);
3117     SSL_shutdown(serverssl);
3118     SSL_free(serverssl);
3119     SSL_free(clientssl);
3120     serverssl = clientssl = NULL;
3121
3122     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3123                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
3124             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
3125                                                    "TLS_AES_256_GCM_SHA384"))
3126             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3127                                              NULL, NULL))
3128             || !TEST_true(SSL_set_session(clientssl, clntsess))
3129                /*
3130                 * We use SSL_ERROR_WANT_READ below so that we can pause the
3131                 * connection after the initial ClientHello has been sent to
3132                 * enable us to make some session changes.
3133                 */
3134             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3135                                                 SSL_ERROR_WANT_READ)))
3136         goto end;
3137
3138     /* Trick the client into thinking this session is for a different digest */
3139     clntsess->cipher = aes_128_gcm_sha256;
3140     clntsess->cipher_id = clntsess->cipher->id;
3141
3142     /*
3143      * Continue the previously started connection. Server has selected a SHA-384
3144      * ciphersuite, but client thinks the session is for SHA-256, so it should
3145      * bail out.
3146      */
3147     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
3148                                                 SSL_ERROR_SSL))
3149             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
3150                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
3151         goto end;
3152
3153     testresult = 1;
3154
3155  end:
3156     SSL_SESSION_free(clntsess);
3157     SSL_free(serverssl);
3158     SSL_free(clientssl);
3159     SSL_CTX_free(sctx);
3160     SSL_CTX_free(cctx);
3161
3162     return testresult;
3163 }
3164
3165 /*
3166  * Test TLSv1.3 PSKs
3167  * Test 0 = Test new style callbacks
3168  * Test 1 = Test both new and old style callbacks
3169  * Test 2 = Test old style callbacks
3170  * Test 3 = Test old style callbacks with no certificate
3171  */
3172 static int test_tls13_psk(int idx)
3173 {
3174     SSL_CTX *sctx = NULL, *cctx = NULL;
3175     SSL *serverssl = NULL, *clientssl = NULL;
3176     const SSL_CIPHER *cipher = NULL;
3177     const unsigned char key[] = {
3178         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
3179         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3180         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
3181         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
3182     };
3183     int testresult = 0;
3184
3185     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3186                                        TLS1_VERSION, TLS_MAX_VERSION,
3187                                        &sctx, &cctx, idx == 3 ? NULL : cert,
3188                                        idx == 3 ? NULL : privkey)))
3189         goto end;
3190
3191     if (idx != 3) {
3192         /*
3193          * We use a ciphersuite with SHA256 to ease testing old style PSK
3194          * callbacks which will always default to SHA256. This should not be
3195          * necessary if we have no cert/priv key. In that case the server should
3196          * prefer SHA256 automatically.
3197          */
3198         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3199                                                 "TLS_AES_128_GCM_SHA256")))
3200             goto end;
3201     }
3202
3203     /*
3204      * Test 0: New style callbacks only
3205      * Test 1: New and old style callbacks (only the new ones should be used)
3206      * Test 2: Old style callbacks only
3207      */
3208     if (idx == 0 || idx == 1) {
3209         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
3210         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
3211     }
3212 #ifndef OPENSSL_NO_PSK
3213     if (idx >= 1) {
3214         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
3215         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
3216     }
3217 #endif
3218     srvid = pskid;
3219     use_session_cb_cnt = 0;
3220     find_session_cb_cnt = 0;
3221     psk_client_cb_cnt = 0;
3222     psk_server_cb_cnt = 0;
3223
3224     if (idx != 3) {
3225         /*
3226          * Check we can create a connection if callback decides not to send a
3227          * PSK
3228          */
3229         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3230                                                  NULL, NULL))
3231                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
3232                                                     SSL_ERROR_NONE))
3233                 || !TEST_false(SSL_session_reused(clientssl))
3234                 || !TEST_false(SSL_session_reused(serverssl)))
3235             goto end;
3236
3237         if (idx == 0 || idx == 1) {
3238             if (!TEST_true(use_session_cb_cnt == 1)
3239                     || !TEST_true(find_session_cb_cnt == 0)
3240                        /*
3241                         * If no old style callback then below should be 0
3242                         * otherwise 1
3243                         */
3244                     || !TEST_true(psk_client_cb_cnt == idx)
3245                     || !TEST_true(psk_server_cb_cnt == 0))
3246                 goto end;
3247         } else {
3248             if (!TEST_true(use_session_cb_cnt == 0)
3249                     || !TEST_true(find_session_cb_cnt == 0)
3250                     || !TEST_true(psk_client_cb_cnt == 1)
3251                     || !TEST_true(psk_server_cb_cnt == 0))
3252                 goto end;
3253         }
3254
3255         shutdown_ssl_connection(serverssl, clientssl);
3256         serverssl = clientssl = NULL;
3257         use_session_cb_cnt = psk_client_cb_cnt = 0;
3258     }
3259
3260     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3261                                              NULL, NULL)))
3262         goto end;
3263
3264     /* Create the PSK */
3265     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
3266     clientpsk = SSL_SESSION_new();
3267     if (!TEST_ptr(clientpsk)
3268             || !TEST_ptr(cipher)
3269             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
3270                                                       sizeof(key)))
3271             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
3272             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
3273                                                            TLS1_3_VERSION))
3274             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
3275         goto end;
3276     serverpsk = clientpsk;
3277
3278     /* Check we can create a connection and the PSK is used */
3279     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3280             || !TEST_true(SSL_session_reused(clientssl))
3281             || !TEST_true(SSL_session_reused(serverssl)))
3282         goto end;
3283
3284     if (idx == 0 || idx == 1) {
3285         if (!TEST_true(use_session_cb_cnt == 1)
3286                 || !TEST_true(find_session_cb_cnt == 1)
3287                 || !TEST_true(psk_client_cb_cnt == 0)
3288                 || !TEST_true(psk_server_cb_cnt == 0))
3289             goto end;
3290     } else {
3291         if (!TEST_true(use_session_cb_cnt == 0)
3292                 || !TEST_true(find_session_cb_cnt == 0)
3293                 || !TEST_true(psk_client_cb_cnt == 1)
3294                 || !TEST_true(psk_server_cb_cnt == 1))
3295             goto end;
3296     }
3297
3298     shutdown_ssl_connection(serverssl, clientssl);
3299     serverssl = clientssl = NULL;
3300     use_session_cb_cnt = find_session_cb_cnt = 0;
3301     psk_client_cb_cnt = psk_server_cb_cnt = 0;
3302
3303     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3304                                              NULL, NULL)))
3305         goto end;
3306
3307     /* Force an HRR */
3308     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
3309         goto end;
3310
3311     /*
3312      * Check we can create a connection, the PSK is used and the callbacks are
3313      * called twice.
3314      */
3315     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3316             || !TEST_true(SSL_session_reused(clientssl))
3317             || !TEST_true(SSL_session_reused(serverssl)))
3318         goto end;
3319
3320     if (idx == 0 || idx == 1) {
3321         if (!TEST_true(use_session_cb_cnt == 2)
3322                 || !TEST_true(find_session_cb_cnt == 2)
3323                 || !TEST_true(psk_client_cb_cnt == 0)
3324                 || !TEST_true(psk_server_cb_cnt == 0))
3325             goto end;
3326     } else {
3327         if (!TEST_true(use_session_cb_cnt == 0)
3328                 || !TEST_true(find_session_cb_cnt == 0)
3329                 || !TEST_true(psk_client_cb_cnt == 2)
3330                 || !TEST_true(psk_server_cb_cnt == 2))
3331             goto end;
3332     }
3333
3334     shutdown_ssl_connection(serverssl, clientssl);
3335     serverssl = clientssl = NULL;
3336     use_session_cb_cnt = find_session_cb_cnt = 0;
3337     psk_client_cb_cnt = psk_server_cb_cnt = 0;
3338
3339     if (idx != 3) {
3340         /*
3341          * Check that if the server rejects the PSK we can still connect, but with
3342          * a full handshake
3343          */
3344         srvid = "Dummy Identity";
3345         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3346                                                  NULL, NULL))
3347                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
3348                                                     SSL_ERROR_NONE))
3349                 || !TEST_false(SSL_session_reused(clientssl))
3350                 || !TEST_false(SSL_session_reused(serverssl)))
3351             goto end;
3352
3353         if (idx == 0 || idx == 1) {
3354             if (!TEST_true(use_session_cb_cnt == 1)
3355                     || !TEST_true(find_session_cb_cnt == 1)
3356                     || !TEST_true(psk_client_cb_cnt == 0)
3357                        /*
3358                         * If no old style callback then below should be 0
3359                         * otherwise 1
3360                         */
3361                     || !TEST_true(psk_server_cb_cnt == idx))
3362                 goto end;
3363         } else {
3364             if (!TEST_true(use_session_cb_cnt == 0)
3365                     || !TEST_true(find_session_cb_cnt == 0)
3366                     || !TEST_true(psk_client_cb_cnt == 1)
3367                     || !TEST_true(psk_server_cb_cnt == 1))
3368                 goto end;
3369         }
3370
3371         shutdown_ssl_connection(serverssl, clientssl);
3372         serverssl = clientssl = NULL;
3373     }
3374     testresult = 1;
3375
3376  end:
3377     SSL_SESSION_free(clientpsk);
3378     SSL_SESSION_free(serverpsk);
3379     clientpsk = serverpsk = NULL;
3380     SSL_free(serverssl);
3381     SSL_free(clientssl);
3382     SSL_CTX_free(sctx);
3383     SSL_CTX_free(cctx);
3384     return testresult;
3385 }
3386
3387 static unsigned char cookie_magic_value[] = "cookie magic";
3388
3389 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
3390                                     unsigned int *cookie_len)
3391 {
3392     /*
3393      * Not suitable as a real cookie generation function but good enough for
3394      * testing!
3395      */
3396     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
3397     *cookie_len = sizeof(cookie_magic_value) - 1;
3398
3399     return 1;
3400 }
3401
3402 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
3403                                   unsigned int cookie_len)
3404 {
3405     if (cookie_len == sizeof(cookie_magic_value) - 1
3406         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
3407         return 1;
3408
3409     return 0;
3410 }
3411
3412 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
3413                                         size_t *cookie_len)
3414 {
3415     unsigned int temp;
3416     int res = generate_cookie_callback(ssl, cookie, &temp);
3417     *cookie_len = temp;
3418     return res;
3419 }
3420
3421 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
3422                                       size_t cookie_len)
3423 {
3424     return verify_cookie_callback(ssl, cookie, cookie_len);
3425 }
3426
3427 static int test_stateless(void)
3428 {
3429     SSL_CTX *sctx = NULL, *cctx = NULL;
3430     SSL *serverssl = NULL, *clientssl = NULL;
3431     int testresult = 0;
3432
3433     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3434                                        TLS1_VERSION, TLS_MAX_VERSION,
3435                                        &sctx, &cctx, cert, privkey)))
3436         goto end;
3437
3438     /* The arrival of CCS messages can confuse the test */
3439     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
3440
3441     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3442                                       NULL, NULL))
3443                /* Send the first ClientHello */
3444             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3445                                                  SSL_ERROR_WANT_READ))
3446                /*
3447                 * This should fail with a -1 return because we have no callbacks
3448                 * set up
3449                 */
3450             || !TEST_int_eq(SSL_stateless(serverssl), -1))
3451         goto end;
3452
3453     /* Fatal error so abandon the connection from this client */
3454     SSL_free(clientssl);
3455     clientssl = NULL;
3456
3457     /* Set up the cookie generation and verification callbacks */
3458     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
3459     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
3460
3461     /*
3462      * Create a new connection from the client (we can reuse the server SSL
3463      * object).
3464      */
3465     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3466                                              NULL, NULL))
3467                /* Send the first ClientHello */
3468             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3469                                                 SSL_ERROR_WANT_READ))
3470                /* This should fail because there is no cookie */
3471             || !TEST_int_eq(SSL_stateless(serverssl), 0))
3472         goto end;
3473
3474     /* Abandon the connection from this client */
3475     SSL_free(clientssl);
3476     clientssl = NULL;
3477
3478     /*
3479      * Now create a connection from a new client but with the same server SSL
3480      * object
3481      */
3482     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3483                                              NULL, NULL))
3484                /* Send the first ClientHello */
3485             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3486                                                 SSL_ERROR_WANT_READ))
3487                /* This should fail because there is no cookie */
3488             || !TEST_int_eq(SSL_stateless(serverssl), 0)
3489                /* Send the second ClientHello */
3490             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3491                                                 SSL_ERROR_WANT_READ))
3492                /* This should succeed because a cookie is now present */
3493             || !TEST_int_eq(SSL_stateless(serverssl), 1)
3494                /* Complete the connection */
3495             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3496                                                 SSL_ERROR_NONE)))
3497         goto end;
3498
3499     shutdown_ssl_connection(serverssl, clientssl);
3500     serverssl = clientssl = NULL;
3501     testresult = 1;
3502
3503  end:
3504     SSL_free(serverssl);
3505     SSL_free(clientssl);
3506     SSL_CTX_free(sctx);
3507     SSL_CTX_free(cctx);
3508     return testresult;
3509
3510 }
3511 #endif /* OPENSSL_NO_TLS1_3 */
3512
3513 static int clntaddoldcb = 0;
3514 static int clntparseoldcb = 0;
3515 static int srvaddoldcb = 0;
3516 static int srvparseoldcb = 0;
3517 static int clntaddnewcb = 0;
3518 static int clntparsenewcb = 0;
3519 static int srvaddnewcb = 0;
3520 static int srvparsenewcb = 0;
3521 static int snicb = 0;
3522
3523 #define TEST_EXT_TYPE1  0xff00
3524
3525 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
3526                       size_t *outlen, int *al, void *add_arg)
3527 {
3528     int *server = (int *)add_arg;
3529     unsigned char *data;
3530
3531     if (SSL_is_server(s))
3532         srvaddoldcb++;
3533     else
3534         clntaddoldcb++;
3535
3536     if (*server != SSL_is_server(s)
3537             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3538         return -1;
3539
3540     *data = 1;
3541     *out = data;
3542     *outlen = sizeof(char);
3543     return 1;
3544 }
3545
3546 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
3547                         void *add_arg)
3548 {
3549     OPENSSL_free((unsigned char *)out);
3550 }
3551
3552 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
3553                         size_t inlen, int *al, void *parse_arg)
3554 {
3555     int *server = (int *)parse_arg;
3556
3557     if (SSL_is_server(s))
3558         srvparseoldcb++;
3559     else
3560         clntparseoldcb++;
3561
3562     if (*server != SSL_is_server(s)
3563             || inlen != sizeof(char)
3564             || *in != 1)
3565         return -1;
3566
3567     return 1;
3568 }
3569
3570 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
3571                       const unsigned char **out, size_t *outlen, X509 *x,
3572                       size_t chainidx, int *al, void *add_arg)
3573 {
3574     int *server = (int *)add_arg;
3575     unsigned char *data;
3576
3577     if (SSL_is_server(s))
3578         srvaddnewcb++;
3579     else
3580         clntaddnewcb++;
3581
3582     if (*server != SSL_is_server(s)
3583             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3584         return -1;
3585
3586     *data = 1;
3587     *out = data;
3588     *outlen = sizeof(*data);
3589     return 1;
3590 }
3591
3592 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
3593                         const unsigned char *out, void *add_arg)
3594 {
3595     OPENSSL_free((unsigned char *)out);
3596 }
3597
3598 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
3599                         const unsigned char *in, size_t inlen, X509 *x,
3600                         size_t chainidx, int *al, void *parse_arg)
3601 {
3602     int *server = (int *)parse_arg;
3603
3604     if (SSL_is_server(s))
3605         srvparsenewcb++;
3606     else
3607         clntparsenewcb++;
3608
3609     if (*server != SSL_is_server(s)
3610             || inlen != sizeof(char) || *in != 1)
3611         return -1;
3612
3613     return 1;
3614 }
3615
3616 static int sni_cb(SSL *s, int *al, void *arg)
3617 {
3618     SSL_CTX *ctx = (SSL_CTX *)arg;
3619
3620     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
3621         *al = SSL_AD_INTERNAL_ERROR;
3622         return SSL_TLSEXT_ERR_ALERT_FATAL;
3623     }
3624     snicb++;
3625     return SSL_TLSEXT_ERR_OK;
3626 }
3627
3628 /*
3629  * Custom call back tests.
3630  * Test 0: Old style callbacks in TLSv1.2
3631  * Test 1: New style callbacks in TLSv1.2
3632  * Test 2: New style callbacks in TLSv1.2 with SNI
3633  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
3634  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
3635  */
3636 static int test_custom_exts(int tst)
3637 {
3638     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
3639     SSL *clientssl = NULL, *serverssl = NULL;
3640     int testresult = 0;
3641     static int server = 1;
3642     static int client = 0;
3643     SSL_SESSION *sess = NULL;
3644     unsigned int context;
3645
3646 #if defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_3)
3647     /* Skip tests for TLSv1.2 and below in this case */
3648     if (tst < 3)
3649         return 1;
3650 #endif
3651
3652     /* Reset callback counters */
3653     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
3654     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
3655     snicb = 0;
3656
3657     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3658                                        TLS1_VERSION, TLS_MAX_VERSION,
3659                                        &sctx, &cctx, cert, privkey)))
3660         goto end;
3661
3662     if (tst == 2
3663             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL,
3664                                               TLS1_VERSION, TLS_MAX_VERSION,
3665                                               &sctx2, NULL, cert, privkey)))
3666         goto end;
3667
3668
3669     if (tst < 3) {
3670         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
3671         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
3672         if (sctx2 != NULL)
3673             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
3674     }
3675
3676     if (tst == 4) {
3677         context = SSL_EXT_CLIENT_HELLO
3678                   | SSL_EXT_TLS1_2_SERVER_HELLO
3679                   | SSL_EXT_TLS1_3_SERVER_HELLO
3680                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
3681                   | SSL_EXT_TLS1_3_CERTIFICATE
3682                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
3683     } else {
3684         context = SSL_EXT_CLIENT_HELLO
3685                   | SSL_EXT_TLS1_2_SERVER_HELLO
3686                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
3687     }
3688
3689     /* Create a client side custom extension */
3690     if (tst == 0) {
3691         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3692                                                      old_add_cb, old_free_cb,
3693                                                      &client, old_parse_cb,
3694                                                      &client)))
3695             goto end;
3696     } else {
3697         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
3698                                               new_add_cb, new_free_cb,
3699                                               &client, new_parse_cb, &client)))
3700             goto end;
3701     }
3702
3703     /* Should not be able to add duplicates */
3704     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3705                                                   old_add_cb, old_free_cb,
3706                                                   &client, old_parse_cb,
3707                                                   &client))
3708             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
3709                                                   context, new_add_cb,
3710                                                   new_free_cb, &client,
3711                                                   new_parse_cb, &client)))
3712         goto end;
3713
3714     /* Create a server side custom extension */
3715     if (tst == 0) {
3716         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3717                                                      old_add_cb, old_free_cb,
3718                                                      &server, old_parse_cb,
3719                                                      &server)))
3720             goto end;
3721     } else {
3722         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
3723                                               new_add_cb, new_free_cb,
3724                                               &server, new_parse_cb, &server)))
3725             goto end;
3726         if (sctx2 != NULL
3727                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
3728                                                      context, new_add_cb,
3729                                                      new_free_cb, &server,
3730                                                      new_parse_cb, &server)))
3731             goto end;
3732     }
3733
3734     /* Should not be able to add duplicates */
3735     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3736                                                   old_add_cb, old_free_cb,
3737                                                   &server, old_parse_cb,
3738                                                   &server))
3739             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
3740                                                   context, new_add_cb,
3741                                                   new_free_cb, &server,
3742                                                   new_parse_cb, &server)))
3743         goto end;
3744
3745     if (tst == 2) {
3746         /* Set up SNI */
3747         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
3748                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
3749             goto end;
3750     }
3751
3752     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3753                                       &clientssl, NULL, NULL))
3754             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3755                                                 SSL_ERROR_NONE)))
3756         goto end;
3757
3758     if (tst == 0) {
3759         if (clntaddoldcb != 1
3760                 || clntparseoldcb != 1
3761                 || srvaddoldcb != 1
3762                 || srvparseoldcb != 1)
3763             goto end;
3764     } else if (tst == 1 || tst == 2 || tst == 3) {
3765         if (clntaddnewcb != 1
3766                 || clntparsenewcb != 1
3767                 || srvaddnewcb != 1
3768                 || srvparsenewcb != 1
3769                 || (tst != 2 && snicb != 0)
3770                 || (tst == 2 && snicb != 1))
3771             goto end;
3772     } else {
3773         /* In this case there 2 NewSessionTicket messages created */
3774         if (clntaddnewcb != 1
3775                 || clntparsenewcb != 5
3776                 || srvaddnewcb != 5
3777                 || srvparsenewcb != 1)
3778             goto end;
3779     }
3780
3781     sess = SSL_get1_session(clientssl);
3782     SSL_shutdown(clientssl);
3783     SSL_shutdown(serverssl);
3784     SSL_free(serverssl);
3785     SSL_free(clientssl);
3786     serverssl = clientssl = NULL;
3787
3788     if (tst == 3) {
3789         /* We don't bother with the resumption aspects for this test */
3790         testresult = 1;
3791         goto end;
3792     }
3793
3794     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3795                                       NULL, NULL))
3796             || !TEST_true(SSL_set_session(clientssl, sess))
3797             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3798                                                SSL_ERROR_NONE)))
3799         goto end;
3800
3801     /*
3802      * For a resumed session we expect to add the ClientHello extension. For the
3803      * old style callbacks we ignore it on the server side because they set
3804      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
3805      * them.
3806      */
3807     if (tst == 0) {
3808         if (clntaddoldcb != 2
3809                 || clntparseoldcb != 1
3810                 || srvaddoldcb != 1
3811                 || srvparseoldcb != 1)
3812             goto end;
3813     } else if (tst == 1 || tst == 2 || tst == 3) {
3814         if (clntaddnewcb != 2
3815                 || clntparsenewcb != 2
3816                 || srvaddnewcb != 2
3817                 || srvparsenewcb != 2)
3818             goto end;
3819     } else {
3820         /*
3821          * No Certificate message extensions in the resumption handshake,
3822          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
3823          */
3824         if (clntaddnewcb != 2
3825                 || clntparsenewcb != 8
3826                 || srvaddnewcb != 8
3827                 || srvparsenewcb != 2)
3828             goto end;
3829     }
3830
3831     testresult = 1;
3832
3833 end:
3834     SSL_SESSION_free(sess);
3835     SSL_free(serverssl);
3836     SSL_free(clientssl);
3837     SSL_CTX_free(sctx2);
3838     SSL_CTX_free(sctx);
3839     SSL_CTX_free(cctx);
3840     return testresult;
3841 }
3842
3843 /*
3844  * Test loading of serverinfo data in various formats. test_sslmessages actually
3845  * tests to make sure the extensions appear in the handshake
3846  */
3847 static int test_serverinfo(int tst)
3848 {
3849     unsigned int version;
3850     unsigned char *sibuf;
3851     size_t sibuflen;
3852     int ret, expected, testresult = 0;
3853     SSL_CTX *ctx;
3854
3855     ctx = SSL_CTX_new(TLS_method());
3856     if (!TEST_ptr(ctx))
3857         goto end;
3858
3859     if ((tst & 0x01) == 0x01)
3860         version = SSL_SERVERINFOV2;
3861     else
3862         version = SSL_SERVERINFOV1;
3863
3864     if ((tst & 0x02) == 0x02) {
3865         sibuf = serverinfov2;
3866         sibuflen = sizeof(serverinfov2);
3867         expected = (version == SSL_SERVERINFOV2);
3868     } else {
3869         sibuf = serverinfov1;
3870         sibuflen = sizeof(serverinfov1);
3871         expected = (version == SSL_SERVERINFOV1);
3872     }
3873
3874     if ((tst & 0x04) == 0x04) {
3875         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
3876     } else {
3877         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
3878
3879         /*
3880          * The version variable is irrelevant in this case - it's what is in the
3881          * buffer that matters
3882          */
3883         if ((tst & 0x02) == 0x02)
3884             expected = 0;
3885         else
3886             expected = 1;
3887     }
3888
3889     if (!TEST_true(ret == expected))
3890         goto end;
3891
3892     testresult = 1;
3893
3894  end:
3895     SSL_CTX_free(ctx);
3896
3897     return testresult;
3898 }
3899
3900 /*
3901  * Test that SSL_export_keying_material() produces expected results. There are
3902  * no test vectors so all we do is test that both sides of the communication
3903  * produce the same results for different protocol versions.
3904  */
3905 static int test_export_key_mat(int tst)
3906 {
3907     int testresult = 0;
3908     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
3909     SSL *clientssl = NULL, *serverssl = NULL;
3910     const char label[] = "test label";
3911     const unsigned char context[] = "context";
3912     const unsigned char *emptycontext = NULL;
3913     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
3914     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
3915     const int protocols[] = {
3916         TLS1_VERSION,
3917         TLS1_1_VERSION,
3918         TLS1_2_VERSION,
3919         TLS1_3_VERSION
3920     };
3921
3922 #ifdef OPENSSL_NO_TLS1
3923     if (tst == 0)
3924         return 1;
3925 #endif
3926 #ifdef OPENSSL_NO_TLS1_1
3927     if (tst == 1)
3928         return 1;
3929 #endif
3930 #ifdef OPENSSL_NO_TLS1_2
3931     if (tst == 2)
3932         return 1;
3933 #endif
3934 #ifdef OPENSSL_NO_TLS1_3
3935     if (tst == 3)
3936         return 1;
3937 #endif
3938     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3939                                        TLS1_VERSION, TLS_MAX_VERSION,
3940                                        &sctx, &cctx, cert, privkey)))
3941         goto end;
3942
3943     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
3944     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
3945     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
3946
3947     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
3948                                       NULL))
3949             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3950                                                 SSL_ERROR_NONE)))
3951         goto end;
3952
3953     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
3954                                                 sizeof(ckeymat1), label,
3955                                                 sizeof(label) - 1, context,
3956                                                 sizeof(context) - 1, 1), 1)
3957             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
3958                                                        sizeof(ckeymat2), label,
3959                                                        sizeof(label) - 1,
3960                                                        emptycontext,
3961                                                        0, 1), 1)
3962             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
3963                                                        sizeof(ckeymat3), label,
3964                                                        sizeof(label) - 1,
3965                                                        NULL, 0, 0), 1)
3966             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
3967                                                        sizeof(skeymat1), label,
3968                                                        sizeof(label) - 1,
3969                                                        context,
3970                                                        sizeof(context) -1, 1),
3971                             1)
3972             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
3973                                                        sizeof(skeymat2), label,
3974                                                        sizeof(label) - 1,
3975                                                        emptycontext,
3976                                                        0, 1), 1)
3977             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
3978                                                        sizeof(skeymat3), label,
3979                                                        sizeof(label) - 1,
3980                                                        NULL, 0, 0), 1)
3981                /*
3982                 * Check that both sides created the same key material with the
3983                 * same context.
3984                 */
3985             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
3986                             sizeof(skeymat1))
3987                /*
3988                 * Check that both sides created the same key material with an
3989                 * empty context.
3990                 */
3991             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
3992                             sizeof(skeymat2))
3993                /*
3994                 * Check that both sides created the same key material without a
3995                 * context.
3996                 */
3997             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
3998                             sizeof(skeymat3))
3999                /* Different contexts should produce different results */
4000             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
4001                             sizeof(ckeymat2)))
4002         goto end;
4003
4004     /*
4005      * Check that an empty context and no context produce different results in
4006      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
4007      */
4008     if ((tst != 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
4009                                   sizeof(ckeymat3)))
4010             || (tst ==3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
4011                                         sizeof(ckeymat3))))
4012         goto end;
4013
4014     testresult = 1;
4015
4016  end:
4017     SSL_free(serverssl);
4018     SSL_free(clientssl);
4019     SSL_CTX_free(sctx2);
4020     SSL_CTX_free(sctx);
4021     SSL_CTX_free(cctx);
4022
4023     return testresult;
4024 }
4025
4026 #ifndef OPENSSL_NO_TLS1_3
4027 /*
4028  * Test that SSL_export_keying_material_early() produces expected
4029  * results. There are no test vectors so all we do is test that both
4030  * sides of the communication produce the same results for different
4031  * protocol versions.
4032  */
4033 static int test_export_key_mat_early(int idx)
4034 {
4035     static const char label[] = "test label";
4036     static const unsigned char context[] = "context";
4037     int testresult = 0;
4038     SSL_CTX *cctx = NULL, *sctx = NULL;
4039     SSL *clientssl = NULL, *serverssl = NULL;
4040     SSL_SESSION *sess = NULL;
4041     const unsigned char *emptycontext = NULL;
4042     unsigned char ckeymat1[80], ckeymat2[80];
4043     unsigned char skeymat1[80], skeymat2[80];
4044     unsigned char buf[1];
4045     size_t readbytes, written;
4046
4047     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
4048                                         &sess, idx)))
4049         goto end;
4050
4051     /* Here writing 0 length early data is enough. */
4052     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
4053             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4054                                                 &readbytes),
4055                             SSL_READ_EARLY_DATA_ERROR)
4056             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4057                             SSL_EARLY_DATA_ACCEPTED))
4058         goto end;
4059
4060     if (!TEST_int_eq(SSL_export_keying_material_early(
4061                      clientssl, ckeymat1, sizeof(ckeymat1), label,
4062                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
4063             || !TEST_int_eq(SSL_export_keying_material_early(
4064                             clientssl, ckeymat2, sizeof(ckeymat2), label,
4065                             sizeof(label) - 1, emptycontext, 0), 1)
4066             || !TEST_int_eq(SSL_export_keying_material_early(
4067                             serverssl, skeymat1, sizeof(skeymat1), label,
4068                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
4069             || !TEST_int_eq(SSL_export_keying_material_early(
4070                             serverssl, skeymat2, sizeof(skeymat2), label,
4071                             sizeof(label) - 1, emptycontext, 0), 1)
4072                /*
4073                 * Check that both sides created the same key material with the
4074                 * same context.
4075                 */
4076             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
4077                             sizeof(skeymat1))
4078                /*
4079                 * Check that both sides created the same key material with an
4080                 * empty context.
4081                 */
4082             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
4083                             sizeof(skeymat2))
4084                /* Different contexts should produce different results */
4085             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
4086                             sizeof(ckeymat2)))
4087         goto end;
4088
4089     testresult = 1;
4090
4091  end:
4092     SSL_SESSION_free(sess);
4093     SSL_SESSION_free(clientpsk);
4094     SSL_SESSION_free(serverpsk);
4095     clientpsk = serverpsk = NULL;
4096     SSL_free(serverssl);
4097     SSL_free(clientssl);
4098     SSL_CTX_free(sctx);
4099     SSL_CTX_free(cctx);
4100
4101     return testresult;
4102 }
4103 #endif /* OPENSSL_NO_TLS1_3 */
4104
4105 static int test_ssl_clear(int idx)
4106 {
4107     SSL_CTX *cctx = NULL, *sctx = NULL;
4108     SSL *clientssl = NULL, *serverssl = NULL;
4109     int testresult = 0;
4110
4111 #ifdef OPENSSL_NO_TLS1_2
4112     if (idx == 1)
4113         return 1;
4114 #endif
4115
4116     /* Create an initial connection */
4117     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4118                                        TLS1_VERSION, TLS_MAX_VERSION,
4119                                        &sctx, &cctx, cert, privkey))
4120             || (idx == 1
4121                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
4122                                                             TLS1_2_VERSION)))
4123             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4124                                           &clientssl, NULL, NULL))
4125             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4126                                                 SSL_ERROR_NONE)))
4127         goto end;
4128
4129     SSL_shutdown(clientssl);
4130     SSL_shutdown(serverssl);
4131     SSL_free(serverssl);
4132     serverssl = NULL;
4133
4134     /* Clear clientssl - we're going to reuse the object */
4135     if (!TEST_true(SSL_clear(clientssl)))
4136         goto end;
4137
4138     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4139                                              NULL, NULL))
4140             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4141                                                 SSL_ERROR_NONE))
4142             || !TEST_true(SSL_session_reused(clientssl)))
4143         goto end;
4144
4145     SSL_shutdown(clientssl);
4146     SSL_shutdown(serverssl);
4147
4148     testresult = 1;
4149
4150  end:
4151     SSL_free(serverssl);
4152     SSL_free(clientssl);
4153     SSL_CTX_free(sctx);
4154     SSL_CTX_free(cctx);
4155
4156     return testresult;
4157 }
4158
4159 /* Parse CH and retrieve any MFL extension value if present */
4160 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
4161 {
4162     long len;
4163     unsigned char *data;
4164     PACKET pkt = {0}, pkt2 = {0}, pkt3 = {0};
4165     unsigned int MFL_code = 0, type = 0;
4166
4167     if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
4168         goto end;
4169
4170     if (!TEST_true( PACKET_buf_init( &pkt, data, len ) )
4171                /* Skip the record header */
4172             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
4173                /* Skip the handshake message header */
4174             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
4175                /* Skip client version and random */
4176             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
4177                                                + SSL3_RANDOM_SIZE))
4178                /* Skip session id */
4179             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
4180                /* Skip ciphers */
4181             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
4182                /* Skip compression */
4183             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
4184                /* Extensions len */
4185             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
4186         goto end;
4187
4188     /* Loop through all extensions */
4189     while (PACKET_remaining(&pkt2)) {
4190         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
4191                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
4192             goto end;
4193
4194         if (type == TLSEXT_TYPE_max_fragment_length) {
4195             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
4196                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
4197                 goto end;
4198
4199             *mfl_codemfl_code = MFL_code;
4200             return 1;
4201         }
4202     }
4203
4204  end:
4205     return 0;
4206 }
4207
4208 /* Maximum-Fragment-Length TLS extension mode to test */
4209 static const unsigned char max_fragment_len_test[] = {
4210     TLSEXT_max_fragment_length_512,
4211     TLSEXT_max_fragment_length_1024,
4212     TLSEXT_max_fragment_length_2048,
4213     TLSEXT_max_fragment_length_4096
4214 };
4215
4216 static int test_max_fragment_len_ext(int idx_tst)
4217 {
4218     SSL_CTX *ctx;
4219     SSL *con = NULL;
4220     int testresult = 0, MFL_mode = 0;
4221     BIO *rbio, *wbio;
4222
4223     ctx = SSL_CTX_new(TLS_method());
4224     if (!TEST_ptr(ctx))
4225         goto end;
4226
4227     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
4228                    ctx, max_fragment_len_test[idx_tst])))
4229         goto end;
4230
4231     con = SSL_new(ctx);
4232     if (!TEST_ptr(con))
4233         goto end;
4234
4235     rbio = BIO_new(BIO_s_mem());
4236     wbio = BIO_new(BIO_s_mem());
4237     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
4238         BIO_free(rbio);
4239         BIO_free(wbio);
4240         goto end;
4241     }
4242
4243     SSL_set_bio(con, rbio, wbio);
4244     SSL_set_connect_state(con);
4245
4246     if (!TEST_int_le(SSL_connect(con), 0)) {
4247         /* This shouldn't succeed because we don't have a server! */
4248         goto end;
4249     }
4250
4251     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
4252         /* no MFL in client hello */
4253         goto end;
4254     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
4255         goto end;
4256
4257     testresult = 1;
4258
4259 end:
4260     SSL_free(con);
4261     SSL_CTX_free(ctx);
4262
4263     return testresult;
4264 }
4265
4266 #ifndef OPENSSL_NO_TLS1_3
4267 static int test_pha_key_update(void)
4268 {
4269     SSL_CTX *cctx = NULL, *sctx = NULL;
4270     SSL *clientssl = NULL, *serverssl = NULL;
4271     int testresult = 0;
4272
4273     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4274                                        TLS1_VERSION, TLS_MAX_VERSION,
4275                                        &sctx, &cctx, cert, privkey)))
4276         return 0;
4277
4278     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
4279         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
4280         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
4281         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
4282         goto end;
4283
4284
4285     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4286                                       NULL, NULL)))
4287         goto end;
4288
4289     SSL_force_post_handshake_auth(clientssl);
4290
4291     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4292                                          SSL_ERROR_NONE)))
4293         goto end;
4294
4295     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
4296     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
4297         goto end;
4298
4299     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
4300         goto end;
4301
4302     /* Start handshake on the server */
4303     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
4304         goto end;
4305
4306     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
4307     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4308                                          SSL_ERROR_NONE)))
4309         goto end;
4310
4311     SSL_shutdown(clientssl);
4312     SSL_shutdown(serverssl);
4313
4314     testresult = 1;
4315
4316  end:
4317     SSL_free(serverssl);
4318     SSL_free(clientssl);
4319     SSL_CTX_free(sctx);
4320     SSL_CTX_free(cctx);
4321     return testresult;
4322 }
4323 #endif
4324
4325 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
4326
4327 static SRP_VBASE *vbase = NULL;
4328
4329 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
4330 {
4331     int ret = SSL3_AL_FATAL;
4332     char *username;
4333     SRP_user_pwd *user = NULL;
4334
4335     username = SSL_get_srp_username(s);
4336     if (username == NULL) {
4337         *ad = SSL_AD_INTERNAL_ERROR;
4338         goto err;
4339     }
4340
4341     user = SRP_VBASE_get1_by_user(vbase, username);
4342     if (user == NULL) {
4343         *ad = SSL_AD_INTERNAL_ERROR;
4344         goto err;
4345     }
4346
4347     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
4348                                  user->info) <= 0) {
4349         *ad = SSL_AD_INTERNAL_ERROR;
4350         goto err;
4351     }
4352
4353     ret = 0;
4354
4355  err:
4356     SRP_user_pwd_free(user);
4357     return ret;
4358 }
4359
4360 static int create_new_vfile(char *userid, char *password, const char *filename)
4361 {
4362     char *gNid = NULL;
4363     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
4364     TXT_DB *db = NULL;
4365     int ret = 0;
4366     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
4367     size_t i;
4368
4369     if (!TEST_ptr(dummy) || !TEST_ptr(row))
4370         goto end;
4371
4372     gNid = SRP_create_verifier(userid, password, &row[DB_srpsalt],
4373                                &row[DB_srpverifier], NULL, NULL);
4374     if (!TEST_ptr(gNid))
4375         goto end;
4376
4377     /*
4378      * The only way to create an empty TXT_DB is to provide a BIO with no data
4379      * in it!
4380      */
4381     db = TXT_DB_read(dummy, DB_NUMBER);
4382     if (!TEST_ptr(db))
4383         goto end;
4384
4385     out = BIO_new_file(filename, "w");
4386     if (!TEST_ptr(out))
4387         goto end;
4388
4389     row[DB_srpid] = OPENSSL_strdup(userid);
4390     row[DB_srptype] = OPENSSL_strdup("V");
4391     row[DB_srpgN] = OPENSSL_strdup(gNid);
4392
4393     if (!TEST_ptr(row[DB_srpid])
4394             || !TEST_ptr(row[DB_srptype])
4395             || !TEST_ptr(row[DB_srpgN])
4396             || !TEST_true(TXT_DB_insert(db, row)))
4397         goto end;
4398
4399     row = NULL;
4400
4401     if (!TXT_DB_write(out, db))
4402         goto end;
4403
4404     ret = 1;
4405  end:
4406     if (row != NULL) {
4407         for (i = 0; i < DB_NUMBER; i++)
4408             OPENSSL_free(row[i]);
4409     }
4410     OPENSSL_free(row);
4411     BIO_free(dummy);
4412     BIO_free(out);
4413     TXT_DB_free(db);
4414
4415     return ret;
4416 }
4417
4418 static int create_new_vbase(char *userid, char *password)
4419 {
4420     BIGNUM *verifier = NULL, *salt = NULL;
4421     const SRP_gN *lgN = NULL;
4422     SRP_user_pwd *user_pwd = NULL;
4423     int ret = 0;
4424
4425     lgN = SRP_get_default_gN(NULL);
4426     if (!TEST_ptr(lgN))
4427         goto end;
4428
4429     if (!TEST_true(SRP_create_verifier_BN(userid, password, &salt, &verifier,
4430                                           lgN->N, lgN->g)))
4431         goto end;
4432
4433     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
4434     if (!TEST_ptr(user_pwd))
4435         goto end;
4436
4437     user_pwd->N = lgN->N;
4438     user_pwd->g = lgN->g;
4439     user_pwd->id = OPENSSL_strdup(userid);
4440     if (!TEST_ptr(user_pwd->id))
4441         goto end;
4442
4443     user_pwd->v = verifier;
4444     user_pwd->s = salt;
4445     verifier = salt = NULL;
4446
4447     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
4448         goto end;
4449     user_pwd = NULL;
4450
4451     ret = 1;
4452 end:
4453     SRP_user_pwd_free(user_pwd);
4454     BN_free(salt);
4455     BN_free(verifier);
4456
4457     return ret;
4458 }
4459
4460 /*
4461  * SRP tests
4462  *
4463  * Test 0: Simple successful SRP connection, new vbase
4464  * Test 1: Connection failure due to bad password, new vbase
4465  * Test 2: Simple successful SRP connection, vbase loaded from existing file
4466  * Test 3: Connection failure due to bad password, vbase loaded from existing
4467  *         file
4468  * Test 4: Simple successful SRP connection, vbase loaded from new file
4469  * Test 5: Connection failure due to bad password, vbase loaded from new file
4470  */
4471 static int test_srp(int tst)
4472 {
4473     char *userid = "test", *password = "password", *tstsrpfile;
4474     SSL_CTX *cctx = NULL, *sctx = NULL;
4475     SSL *clientssl = NULL, *serverssl = NULL;
4476     int ret, testresult = 0;
4477
4478     vbase = SRP_VBASE_new(NULL);
4479     if (!TEST_ptr(vbase))
4480         goto end;
4481
4482     if (tst == 0 || tst == 1) {
4483         if (!TEST_true(create_new_vbase(userid, password)))
4484             goto end;
4485     } else {
4486         if (tst == 4 || tst == 5) {
4487             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
4488                 goto end;
4489             tstsrpfile = tmpfilename;
4490         } else {
4491             tstsrpfile = srpvfile;
4492         }
4493         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
4494             goto end;
4495     }
4496
4497     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4498                                        TLS1_VERSION, TLS_MAX_VERSION,
4499                                        &sctx, &cctx, cert, privkey)))
4500         goto end;
4501
4502     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
4503             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
4504             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
4505             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
4506             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
4507         goto end;
4508
4509     if (tst % 2 == 1) {
4510         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
4511             goto end;
4512     } else {
4513         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
4514             goto end;
4515     }
4516
4517     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4518                                       NULL, NULL)))
4519         goto end;
4520
4521     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
4522     if (ret) {
4523         if (!TEST_true(tst % 2 == 0))
4524             goto end;
4525     } else {
4526         if (!TEST_true(tst % 2 == 1))
4527             goto end;
4528     }
4529
4530     testresult = 1;
4531
4532  end:
4533     SRP_VBASE_free(vbase);
4534     vbase = NULL;
4535     SSL_free(serverssl);
4536     SSL_free(clientssl);
4537     SSL_CTX_free(sctx);
4538     SSL_CTX_free(cctx);
4539
4540     return testresult;
4541 }
4542 #endif
4543
4544 static int info_cb_failed = 0;
4545 static int info_cb_offset = 0;
4546 static int info_cb_this_state = -1;
4547
4548 static struct info_cb_states_st {
4549     int where;
4550     const char *statestr;
4551 } info_cb_states[][60] = {
4552     {
4553         /* TLSv1.2 server followed by resumption */
4554         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4555         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4556         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
4557         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
4558         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
4559         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
4560         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4561         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4562         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
4563         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
4564         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
4565         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4566         {SSL_CB_EXIT, NULL}, {0, NULL},
4567     }, {
4568         /* TLSv1.2 client followed by resumption */
4569         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4570         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
4571         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
4572         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
4573         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
4574         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
4575         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
4576         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4577         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
4578         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
4579         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
4580         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4581     }, {
4582         /* TLSv1.3 server followed by resumption */
4583         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4584         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4585         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
4586         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
4587         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
4588         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4589         {SSL_CB_LOOP, "TWST"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4590         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TWST"},
4591         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4592         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4593         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
4594         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"},
4595         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL},
4596         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
4597         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4598         {SSL_CB_LOOP, "TWST"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4599         {SSL_CB_EXIT, NULL}, {0, NULL},
4600     }, {
4601         /* TLSv1.3 client followed by resumption */
4602         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4603         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
4604         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
4605         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
4606         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
4607         {SSL_CB_EXIT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4608         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4609         {SSL_CB_HANDSHAKE_DONE, NULL},  {SSL_CB_EXIT, NULL},
4610         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "SSLOK "},
4611         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4612         {SSL_CB_HANDSHAKE_DONE, NULL},  {SSL_CB_EXIT, NULL},
4613         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4614         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
4615         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
4616         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
4617         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4618         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "SSLOK "},
4619         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4620         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4621     }, {
4622         /* TLSv1.3 server, early_data */
4623         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4624         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4625         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
4626         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4627         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
4628         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
4629         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4630         {SSL_CB_LOOP, "TWST"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4631         {SSL_CB_EXIT, NULL}, {0, NULL},
4632     }, {
4633         /* TLSv1.3 client, early_data */
4634         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4635         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
4636         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4637         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
4638         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
4639         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
4640         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4641         {SSL_CB_EXIT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4642         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4643         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4644     }, {
4645         {0, NULL},
4646     }
4647 };
4648
4649 static void sslapi_info_callback(const SSL *s, int where, int ret)
4650 {
4651     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
4652
4653     /* We do not ever expect a connection to fail in this test */
4654     if (!TEST_false(ret == 0)) {
4655         info_cb_failed = 1;
4656         return;
4657     }
4658
4659     /*
4660      * Do some sanity checks. We never expect these things to happen in this
4661      * test
4662      */
4663     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
4664             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
4665             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
4666         info_cb_failed = 1;
4667         return;
4668     }
4669
4670     /* Now check we're in the right state */
4671     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
4672         info_cb_failed = 1;
4673         return;
4674     }
4675     if ((where & SSL_CB_LOOP) != 0
4676             && !TEST_int_eq(strcmp(SSL_state_string(s),
4677                             state[info_cb_this_state].statestr), 0)) {
4678         info_cb_failed = 1;
4679         return;
4680     }
4681
4682     /* Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init */
4683     if ((where & SSL_CB_HANDSHAKE_DONE) && SSL_in_init((SSL *)s) != 0) {
4684         info_cb_failed = 1;
4685         return;
4686     }
4687 }
4688
4689 /*
4690  * Test the info callback gets called when we expect it to.
4691  *
4692  * Test 0: TLSv1.2, server
4693  * Test 1: TLSv1.2, client
4694  * Test 2: TLSv1.3, server
4695  * Test 3: TLSv1.3, client
4696  * Test 4: TLSv1.3, server, early_data
4697  * Test 5: TLSv1.3, client, early_data
4698  */
4699 static int test_info_callback(int tst)
4700 {
4701     SSL_CTX *cctx = NULL, *sctx = NULL;
4702     SSL *clientssl = NULL, *serverssl = NULL;
4703     SSL_SESSION *clntsess = NULL;
4704     int testresult = 0;
4705     int tlsvers;
4706
4707     if (tst < 2) {
4708 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
4709 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
4710                                     || !defined(OPENSSL_NO_DH))
4711         tlsvers = TLS1_2_VERSION;
4712 #else
4713         return 1;
4714 #endif
4715     } else {
4716 #ifndef OPENSSL_NO_TLS1_3
4717         tlsvers = TLS1_3_VERSION;
4718 #else
4719         return 1;
4720 #endif
4721     }
4722
4723     /* Reset globals */
4724     info_cb_failed = 0;
4725     info_cb_this_state = -1;
4726     info_cb_offset = tst;
4727
4728 #ifndef OPENSSL_NO_TLS1_3
4729     if (tst >= 4) {
4730         SSL_SESSION *sess = NULL;
4731         size_t written, readbytes;
4732         unsigned char buf[80];
4733
4734         /* early_data tests */
4735         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4736                                             &serverssl, &sess, 0)))
4737             goto end;
4738
4739         /* We don't actually need this reference */
4740         SSL_SESSION_free(sess);
4741
4742         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
4743                               sslapi_info_callback);
4744
4745         /* Write and read some early data and then complete the connection */
4746         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4747                                             &written))
4748                 || !TEST_size_t_eq(written, strlen(MSG1))
4749                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
4750                                                     sizeof(buf), &readbytes),
4751                                 SSL_READ_EARLY_DATA_SUCCESS)
4752                 || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
4753                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4754                                 SSL_EARLY_DATA_ACCEPTED)
4755                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
4756                                                     SSL_ERROR_NONE))
4757                 || !TEST_false(info_cb_failed))
4758             goto end;
4759
4760         testresult = 1;
4761         goto end;
4762     }
4763 #endif
4764
4765     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4766                                        TLS_client_method(),
4767                                        tlsvers, tlsvers, &sctx, &cctx, cert,
4768                                        privkey)))
4769         goto end;
4770
4771     /*
4772      * For even numbered tests we check the server callbacks. For odd numbers we
4773      * check the client.
4774      */
4775     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
4776                               sslapi_info_callback);
4777
4778     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4779                                           &clientssl, NULL, NULL))
4780         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4781                                             SSL_ERROR_NONE))
4782         || !TEST_false(info_cb_failed))
4783     goto end;
4784
4785
4786
4787     clntsess = SSL_get1_session(clientssl);
4788     SSL_shutdown(clientssl);
4789     SSL_shutdown(serverssl);
4790     SSL_free(serverssl);
4791     SSL_free(clientssl);
4792     serverssl = clientssl = NULL;
4793
4794     /* Now do a resumption */
4795     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
4796                                       NULL))
4797             || !TEST_true(SSL_set_session(clientssl, clntsess))
4798             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4799                                                 SSL_ERROR_NONE))
4800             || !TEST_true(SSL_session_reused(clientssl))
4801             || !TEST_false(info_cb_failed))
4802         goto end;
4803
4804     testresult = 1;
4805
4806  end:
4807     SSL_free(serverssl);
4808     SSL_free(clientssl);
4809     SSL_SESSION_free(clntsess);
4810     SSL_CTX_free(sctx);
4811     SSL_CTX_free(cctx);
4812     return testresult;
4813 }
4814
4815 static int test_ssl_pending(int tst)
4816 {
4817     SSL_CTX *cctx = NULL, *sctx = NULL;
4818     SSL *clientssl = NULL, *serverssl = NULL;
4819     int testresult = 0;
4820     char msg[] = "A test message";
4821     char buf[5];
4822     size_t written, readbytes;
4823
4824     if (tst == 0) {
4825         if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4826                                            TLS_client_method(),
4827                                            TLS1_VERSION, TLS_MAX_VERSION,
4828                                            &sctx, &cctx, cert, privkey)))
4829             goto end;
4830     } else {
4831 #ifndef OPENSSL_NO_DTLS
4832         if (!TEST_true(create_ssl_ctx_pair(DTLS_server_method(),
4833                                            DTLS_client_method(),
4834                                            DTLS1_VERSION, DTLS_MAX_VERSION,
4835                                            &sctx, &cctx, cert, privkey)))
4836             goto end;
4837 #else
4838         return 1;
4839 #endif
4840     }
4841
4842     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4843                                              NULL, NULL))
4844             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4845                                                 SSL_ERROR_NONE)))
4846         goto end;
4847
4848     if (!TEST_int_eq(SSL_pending(clientssl), 0)
4849             || !TEST_false(SSL_has_pending(clientssl))
4850             || !TEST_int_eq(SSL_pending(serverssl), 0)
4851             || !TEST_false(SSL_has_pending(serverssl))
4852             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
4853             || !TEST_size_t_eq(written, sizeof(msg))
4854             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
4855             || !TEST_size_t_eq(readbytes, sizeof(buf))
4856             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
4857             || !TEST_true(SSL_has_pending(clientssl)))
4858         goto end;
4859
4860     testresult = 1;
4861
4862  end:
4863     SSL_free(serverssl);
4864     SSL_free(clientssl);
4865     SSL_CTX_free(sctx);
4866     SSL_CTX_free(cctx);
4867
4868     return testresult;
4869 }
4870
4871 static struct {
4872     unsigned int maxprot;
4873     const char *clntciphers;
4874     const char *clnttls13ciphers;
4875     const char *srvrciphers;
4876     const char *srvrtls13ciphers;
4877     const char *shared;
4878 } shared_ciphers_data[] = {
4879 /*
4880  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
4881  * TLSv1.3 is enabled but TLSv1.2 is disabled.
4882  */
4883 #if defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
4884     {
4885         TLS1_2_VERSION,
4886         "AES128-SHA:AES256-SHA",
4887         NULL,
4888         "AES256-SHA:DHE-RSA-AES128-SHA",
4889         NULL,
4890         "AES256-SHA"
4891     },
4892     {
4893         TLS1_2_VERSION,
4894         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
4895         NULL,
4896         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
4897         NULL,
4898         "AES128-SHA:AES256-SHA"
4899     },
4900     {
4901         TLS1_2_VERSION,
4902         "AES128-SHA:AES256-SHA",
4903         NULL,
4904         "AES128-SHA:DHE-RSA-AES128-SHA",
4905         NULL,
4906         "AES128-SHA"
4907     },
4908 #endif
4909 /*
4910  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
4911  * enabled.
4912  */
4913 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
4914     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4915     {
4916         TLS1_3_VERSION,
4917         "AES128-SHA:AES256-SHA",
4918         NULL,
4919         "AES256-SHA:AES128-SHA256",
4920         NULL,
4921         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
4922         "TLS_AES_128_GCM_SHA256:AES256-SHA"
4923     },
4924 #endif
4925 #ifndef OPENSSL_NO_TLS1_3
4926     {
4927         TLS1_3_VERSION,
4928         "AES128-SHA",
4929         "TLS_AES_256_GCM_SHA384",
4930         "AES256-SHA",
4931         "TLS_AES_256_GCM_SHA384",
4932         "TLS_AES_256_GCM_SHA384"
4933     },
4934 #endif
4935 };
4936
4937 static int test_ssl_get_shared_ciphers(int tst)
4938 {
4939     SSL_CTX *cctx = NULL, *sctx = NULL;
4940     SSL *clientssl = NULL, *serverssl = NULL;
4941     int testresult = 0;
4942     char buf[1024];
4943
4944     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4945                                        TLS_client_method(),
4946                                        TLS1_VERSION,
4947                                        shared_ciphers_data[tst].maxprot,
4948                                        &sctx, &cctx, cert, privkey)))
4949         goto end;
4950
4951     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
4952                                         shared_ciphers_data[tst].clntciphers))
4953             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
4954                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
4955                                     shared_ciphers_data[tst].clnttls13ciphers)))
4956             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
4957                                         shared_ciphers_data[tst].srvrciphers))
4958             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
4959                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4960                                     shared_ciphers_data[tst].srvrtls13ciphers))))
4961         goto end;
4962
4963
4964     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4965                                              NULL, NULL))
4966             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4967                                                 SSL_ERROR_NONE)))
4968         goto end;
4969
4970     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
4971             || !TEST_int_eq(strcmp(buf, shared_ciphers_data[tst].shared), 0)) {
4972         TEST_info("Shared ciphers are: %s\n", buf);
4973         goto end;
4974     }
4975
4976     testresult = 1;
4977
4978  end:
4979     SSL_free(serverssl);
4980     SSL_free(clientssl);
4981     SSL_CTX_free(sctx);
4982     SSL_CTX_free(cctx);
4983
4984     return testresult;
4985 }
4986
4987 static const char *appdata = "Hello World";
4988 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
4989 static int tick_key_renew = 0;
4990 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
4991
4992 static int gen_tick_cb(SSL *s, void *arg)
4993 {
4994     gen_tick_called = 1;
4995
4996     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
4997                                            strlen(appdata));
4998 }
4999
5000 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
5001                                      const unsigned char *keyname,
5002                                      size_t keyname_length,
5003                                      SSL_TICKET_STATUS status,
5004                                      void *arg)
5005 {
5006     void *tickdata;
5007     size_t tickdlen;
5008
5009     dec_tick_called = 1;
5010
5011     if (status == SSL_TICKET_EMPTY)
5012         return SSL_TICKET_RETURN_IGNORE_RENEW;
5013
5014     if (!TEST_true(status == SSL_TICKET_SUCCESS
5015                    || status == SSL_TICKET_SUCCESS_RENEW))
5016         return SSL_TICKET_RETURN_ABORT;
5017
5018     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
5019                                                    &tickdlen))
5020             || !TEST_size_t_eq(tickdlen, strlen(appdata))
5021             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
5022         return SSL_TICKET_RETURN_ABORT;
5023
5024     if (tick_key_cb_called)  {
5025         /* Don't change what the ticket key callback wanted to do */
5026         switch (status) {
5027         case SSL_TICKET_NO_DECRYPT:
5028             return SSL_TICKET_RETURN_IGNORE_RENEW;
5029
5030         case SSL_TICKET_SUCCESS:
5031             return SSL_TICKET_RETURN_USE;
5032
5033         case SSL_TICKET_SUCCESS_RENEW:
5034             return SSL_TICKET_RETURN_USE_RENEW;
5035
5036         default:
5037             return SSL_TICKET_RETURN_ABORT;
5038         }
5039     }
5040     return tick_dec_ret;
5041
5042 }
5043
5044 static int tick_key_cb(SSL *s, unsigned char key_name[16],
5045                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
5046                        HMAC_CTX *hctx, int enc)
5047 {
5048     const unsigned char tick_aes_key[16] = "0123456789abcdef";
5049     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
5050
5051     tick_key_cb_called = 1;
5052     memset(iv, 0, AES_BLOCK_SIZE);
5053     memset(key_name, 0, 16);
5054     if (!EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, tick_aes_key, iv, enc)
5055             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key),
5056                              EVP_sha256(), NULL))
5057         return -1;
5058
5059     return tick_key_renew ? 2 : 1;
5060 }
5061
5062 /*
5063  * Test the various ticket callbacks
5064  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
5065  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
5066  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
5067  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
5068  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
5069  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
5070  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
5071  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
5072  * Test 8: TLSv1.2, ticket key callback, ticket, no renewal
5073  * Test 9: TLSv1.3, ticket key callback, ticket, no renewal
5074  * Test 10: TLSv1.2, ticket key callback, ticket, renewal
5075  * Test 11: TLSv1.3, ticket key callback, ticket, renewal
5076  */
5077 static int test_ticket_callbacks(int tst)
5078 {
5079     SSL_CTX *cctx = NULL, *sctx = NULL;
5080     SSL *clientssl = NULL, *serverssl = NULL;
5081     SSL_SESSION *clntsess = NULL;
5082     int testresult = 0;
5083
5084 #ifdef OPENSSL_NO_TLS1_2
5085     if (tst % 2 == 0)
5086         return 1;
5087 #endif
5088 #ifdef OPENSSL_NO_TLS1_3
5089     if (tst % 2 == 1)
5090         return 1;
5091 #endif
5092
5093     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
5094
5095     /* Which tests the ticket key callback should request renewal for */
5096     if (tst == 10 || tst == 11)
5097         tick_key_renew = 1;
5098     else
5099         tick_key_renew = 0;
5100
5101     /* Which tests the decrypt ticket callback should request renewal for */
5102     switch (tst) {
5103     case 0:
5104     case 1:
5105         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
5106         break;
5107
5108     case 2:
5109     case 3:
5110         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
5111         break;
5112
5113     case 4:
5114     case 5:
5115         tick_dec_ret = SSL_TICKET_RETURN_USE;
5116         break;
5117
5118     case 6:
5119     case 7:
5120         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
5121         break;
5122
5123     default:
5124         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
5125     }
5126
5127     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5128                                        TLS_client_method(),
5129                                        TLS1_VERSION,
5130                                        ((tst % 2) == 0) ? TLS1_2_VERSION
5131                                                         : TLS1_3_VERSION,
5132                                        &sctx, &cctx, cert, privkey)))
5133         goto end;
5134
5135     /*
5136      * We only want sessions to resume from tickets - not the session cache. So
5137      * switch the cache off.
5138      */
5139     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
5140         goto end;
5141
5142     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
5143                                                  NULL)))
5144         goto end;
5145
5146     if (tst >= 8
5147             && !TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
5148         goto end;
5149
5150     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5151                                              NULL, NULL))
5152             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5153                                                 SSL_ERROR_NONE)))
5154         goto end;
5155
5156     /*
5157      * The decrypt ticket key callback in TLSv1.2 should be called even though
5158      * we have no ticket yet, because it gets called with a status of
5159      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
5160      * actually send any ticket data). This does not happen in TLSv1.3 because
5161      * it is not valid to send empty ticket data in TLSv1.3.
5162      */
5163     if (!TEST_int_eq(gen_tick_called, 1)
5164             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
5165         goto end;
5166
5167     gen_tick_called = dec_tick_called = 0;
5168
5169     clntsess = SSL_get1_session(clientssl);
5170     SSL_shutdown(clientssl);
5171     SSL_shutdown(serverssl);
5172     SSL_free(serverssl);
5173     SSL_free(clientssl);
5174     serverssl = clientssl = NULL;
5175
5176     /* Now do a resumption */
5177     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
5178                                       NULL))
5179             || !TEST_true(SSL_set_session(clientssl, clntsess))
5180             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5181                                                 SSL_ERROR_NONE)))
5182         goto end;
5183
5184     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
5185             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW) {
5186         if (!TEST_false(SSL_session_reused(clientssl)))
5187             goto end;
5188     } else {
5189         if (!TEST_true(SSL_session_reused(clientssl)))
5190             goto end;
5191     }
5192
5193     if (!TEST_int_eq(gen_tick_called,
5194                      (tick_key_renew
5195                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
5196                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
5197                      ? 1 : 0)
5198             || !TEST_int_eq(dec_tick_called, 1))
5199         goto end;
5200
5201     testresult = 1;
5202
5203  end:
5204     SSL_SESSION_free(clntsess);
5205     SSL_free(serverssl);
5206     SSL_free(clientssl);
5207     SSL_CTX_free(sctx);
5208     SSL_CTX_free(cctx);
5209
5210     return testresult;
5211 }
5212
5213 /*
5214  * Test bi-directional shutdown.
5215  * Test 0: TLSv1.2
5216  * Test 1: TLSv1.2, server continues to read/write after client shutdown
5217  * Test 2: TLSv1.3, no pending NewSessionTicket messages
5218  * Test 3: TLSv1.3, pending NewSessionTicket messages
5219  * Test 4: TLSv1.3, server continues to read/write after client shutdown, client
5220  *                  reads it
5221  * Test 5: TLSv1.3, server continues to read/write after client shutdown, client
5222  *                  doesn't read it
5223  */
5224 static int test_shutdown(int tst)
5225 {
5226     SSL_CTX *cctx = NULL, *sctx = NULL;
5227     SSL *clientssl = NULL, *serverssl = NULL;
5228     int testresult = 0;
5229     char msg[] = "A test message";
5230     char buf[80];
5231     size_t written, readbytes;
5232
5233 #ifdef OPENSSL_NO_TLS1_2
5234     if (tst <= 1)
5235         return 1;
5236 #endif
5237 #ifdef OPENSSL_NO_TLS1_3
5238     if (tst >= 2)
5239         return 1;
5240 #endif
5241
5242     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5243                                        TLS_client_method(),
5244                                        TLS1_VERSION,
5245                                        (tst <= 1) ? TLS1_2_VERSION
5246                                                   : TLS1_3_VERSION,
5247                                        &sctx, &cctx, cert, privkey))
5248             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5249                                              NULL, NULL)))
5250         goto end;
5251
5252     if (tst == 3) {
5253         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
5254                                                   SSL_ERROR_NONE)))
5255             goto end;
5256     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5257                                               SSL_ERROR_NONE))) {
5258         goto end;
5259     }
5260
5261     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
5262         goto end;
5263
5264     if (tst >= 4) {
5265         /*
5266          * Reading on the server after the client has sent close_notify should
5267          * fail and provide SSL_ERROR_ZERO_RETURN
5268          */
5269         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
5270                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
5271                                 SSL_ERROR_ZERO_RETURN)
5272                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
5273                                 SSL_RECEIVED_SHUTDOWN)
5274                    /*
5275                     * Even though we're shutdown on receive we should still be
5276                     * able to write.
5277                     */
5278                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg)))
5279                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
5280             goto end;
5281         if (tst == 4) {
5282                    /* Should still be able to read data from server */
5283             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
5284                                           &readbytes))
5285                     || !TEST_size_t_eq(readbytes, sizeof(msg))
5286                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
5287                 goto end;
5288         }
5289     }
5290
5291     /* Writing on the client after sending close_notify shouldn't be possible */
5292     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
5293         goto end;
5294
5295     if (tst < 4) {
5296         /*
5297          * For these tests the client has sent close_notify but it has not yet
5298          * been received by the server. The server has not sent close_notify
5299          * yet.
5300          */
5301         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
5302                    /*
5303                     * Writing on the server after sending close_notify shouldn't
5304                     * be possible.
5305                     */
5306                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
5307                 || !TEST_int_eq(SSL_shutdown(clientssl), 1)
5308                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
5309             goto end;
5310     } else if (tst == 4) {
5311         /*
5312          * In this test the client has sent close_notify and it has been
5313          * received by the server which has responded with a close_notify. The
5314          * client needs to read the close_notify sent by the server.
5315          */
5316         if (!TEST_int_eq(SSL_shutdown(clientssl), 1))
5317             goto end;
5318     } else {
5319         /*
5320          * tst == 5
5321          *
5322          * The client has sent close_notify and is expecting a close_notify
5323          * back, but instead there is application data first. The shutdown
5324          * should fail with a fatal error.
5325          */
5326         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
5327                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
5328             goto end;
5329     }
5330
5331     testresult = 1;
5332
5333  end:
5334     SSL_free(serverssl);
5335     SSL_free(clientssl);
5336     SSL_CTX_free(sctx);
5337     SSL_CTX_free(cctx);
5338
5339     return testresult;
5340 }
5341
5342 int setup_tests(void)
5343 {
5344     if (!TEST_ptr(cert = test_get_argument(0))
5345             || !TEST_ptr(privkey = test_get_argument(1))
5346             || !TEST_ptr(srpvfile = test_get_argument(2))
5347             || !TEST_ptr(tmpfilename = test_get_argument(3)))
5348         return 0;
5349
5350     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
5351 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
5352         TEST_error("not supported in this build");
5353         return 0;
5354 #else
5355         int i, mcount, rcount, fcount;
5356
5357         for (i = 0; i < 4; i++)
5358             test_export_key_mat(i);
5359         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
5360         test_printf_stdout("malloc %d realloc %d free %d\n",
5361                 mcount, rcount, fcount);
5362         return 1;
5363 #endif
5364     }
5365
5366     ADD_TEST(test_large_message_tls);
5367     ADD_TEST(test_large_message_tls_read_ahead);
5368 #ifndef OPENSSL_NO_DTLS
5369     ADD_TEST(test_large_message_dtls);
5370 #endif
5371 #ifndef OPENSSL_NO_OCSP
5372     ADD_TEST(test_tlsext_status_type);
5373 #endif
5374     ADD_TEST(test_session_with_only_int_cache);
5375     ADD_TEST(test_session_with_only_ext_cache);
5376     ADD_TEST(test_session_with_both_cache);
5377 #ifndef OPENSSL_NO_TLS1_3
5378     ADD_ALL_TESTS(test_stateful_tickets, 3);
5379     ADD_ALL_TESTS(test_stateless_tickets, 3);
5380 #endif
5381     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
5382     ADD_TEST(test_ssl_bio_pop_next_bio);
5383     ADD_TEST(test_ssl_bio_pop_ssl_bio);
5384     ADD_TEST(test_ssl_bio_change_rbio);
5385     ADD_TEST(test_ssl_bio_change_wbio);
5386 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
5387     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
5388     ADD_TEST(test_keylog);
5389 #endif
5390 #ifndef OPENSSL_NO_TLS1_3
5391     ADD_TEST(test_keylog_no_master_key);
5392 #endif
5393 #ifndef OPENSSL_NO_TLS1_2
5394     ADD_TEST(test_client_hello_cb);
5395 #endif
5396 #ifndef OPENSSL_NO_TLS1_3
5397     ADD_ALL_TESTS(test_early_data_read_write, 3);
5398     /*
5399      * We don't do replay tests for external PSK. Replay protection isn't used
5400      * in that scenario.
5401      */
5402     ADD_ALL_TESTS(test_early_data_replay, 2);
5403     ADD_ALL_TESTS(test_early_data_skip, 3);
5404     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
5405     ADD_ALL_TESTS(test_early_data_skip_abort, 3);
5406     ADD_ALL_TESTS(test_early_data_not_sent, 3);
5407     ADD_ALL_TESTS(test_early_data_psk, 8);
5408     ADD_ALL_TESTS(test_early_data_not_expected, 3);
5409 # ifndef OPENSSL_NO_TLS1_2
5410     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
5411 # endif
5412 #endif
5413 #ifndef OPENSSL_NO_TLS1_3
5414     ADD_ALL_TESTS(test_set_ciphersuite, 10);
5415     ADD_TEST(test_ciphersuite_change);
5416 #ifdef OPENSSL_NO_PSK
5417     ADD_ALL_TESTS(test_tls13_psk, 1);
5418 #else
5419     ADD_ALL_TESTS(test_tls13_psk, 4);
5420 #endif  /* OPENSSL_NO_PSK */
5421     ADD_ALL_TESTS(test_custom_exts, 5);
5422     ADD_TEST(test_stateless);
5423     ADD_TEST(test_pha_key_update);
5424 #else
5425     ADD_ALL_TESTS(test_custom_exts, 3);
5426 #endif
5427     ADD_ALL_TESTS(test_serverinfo, 8);
5428     ADD_ALL_TESTS(test_export_key_mat, 4);
5429 #ifndef OPENSSL_NO_TLS1_3
5430     ADD_ALL_TESTS(test_export_key_mat_early, 3);
5431 #endif
5432     ADD_ALL_TESTS(test_ssl_clear, 2);
5433     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
5434 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
5435     ADD_ALL_TESTS(test_srp, 6);
5436 #endif
5437     ADD_ALL_TESTS(test_info_callback, 6);
5438     ADD_ALL_TESTS(test_ssl_pending, 2);
5439     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
5440     ADD_ALL_TESTS(test_ticket_callbacks, 12);
5441     ADD_ALL_TESTS(test_shutdown, 6);
5442     return 1;
5443 }
5444
5445 void cleanup_tests(void)
5446 {
5447     bio_s_mempacket_test_free();
5448 }