Imported Upstream version 1.1.1l
[platform/upstream/openssl1.1.git] / test / sslapitest.c
1 /*
2  * Copyright 2016-2021 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 #include <openssl/x509v3.h>
21
22 #include "ssltestlib.h"
23 #include "testutil.h"
24 #include "testutil/output.h"
25 #include "internal/nelem.h"
26 #include "../ssl/ssl_local.h"
27
28 #ifndef OPENSSL_NO_TLS1_3
29
30 static SSL_SESSION *clientpsk = NULL;
31 static SSL_SESSION *serverpsk = NULL;
32 static const char *pskid = "Identity";
33 static const char *srvid;
34
35 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
36                           size_t *idlen, SSL_SESSION **sess);
37 static int find_session_cb(SSL *ssl, const unsigned char *identity,
38                            size_t identity_len, SSL_SESSION **sess);
39
40 static int use_session_cb_cnt = 0;
41 static int find_session_cb_cnt = 0;
42
43 static SSL_SESSION *create_a_psk(SSL *ssl);
44 #endif
45
46 static char *certsdir = NULL;
47 static char *cert = NULL;
48 static char *privkey = NULL;
49 static char *srpvfile = NULL;
50 static char *tmpfilename = NULL;
51
52 #define LOG_BUFFER_SIZE 2048
53 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
54 static size_t server_log_buffer_index = 0;
55 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
56 static size_t client_log_buffer_index = 0;
57 static int error_writing_log = 0;
58
59 #ifndef OPENSSL_NO_OCSP
60 static const unsigned char orespder[] = "Dummy OCSP Response";
61 static int ocsp_server_called = 0;
62 static int ocsp_client_called = 0;
63
64 static int cdummyarg = 1;
65 static X509 *ocspcert = NULL;
66 #endif
67
68 #define NUM_EXTRA_CERTS 40
69 #define CLIENT_VERSION_LEN      2
70
71 /*
72  * This structure is used to validate that the correct number of log messages
73  * of various types are emitted when emitting secret logs.
74  */
75 struct sslapitest_log_counts {
76     unsigned int rsa_key_exchange_count;
77     unsigned int master_secret_count;
78     unsigned int client_early_secret_count;
79     unsigned int client_handshake_secret_count;
80     unsigned int server_handshake_secret_count;
81     unsigned int client_application_secret_count;
82     unsigned int server_application_secret_count;
83     unsigned int early_exporter_secret_count;
84     unsigned int exporter_secret_count;
85 };
86
87
88 static unsigned char serverinfov1[] = {
89     0xff, 0xff, /* Dummy extension type */
90     0x00, 0x01, /* Extension length is 1 byte */
91     0xff        /* Dummy extension data */
92 };
93
94 static unsigned char serverinfov2[] = {
95     0x00, 0x00, 0x00,
96     (unsigned char)(SSL_EXT_CLIENT_HELLO & 0xff), /* Dummy context - 4 bytes */
97     0xff, 0xff, /* Dummy extension type */
98     0x00, 0x01, /* Extension length is 1 byte */
99     0xff        /* Dummy extension data */
100 };
101
102 static int hostname_cb(SSL *s, int *al, void *arg)
103 {
104     const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
105
106     if (hostname != NULL && (strcmp(hostname, "goodhost") == 0
107                              || strcmp(hostname, "altgoodhost") == 0))
108         return  SSL_TLSEXT_ERR_OK;
109
110     return SSL_TLSEXT_ERR_NOACK;
111 }
112
113 static void client_keylog_callback(const SSL *ssl, const char *line)
114 {
115     int line_length = strlen(line);
116
117     /* If the log doesn't fit, error out. */
118     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
119         TEST_info("Client log too full");
120         error_writing_log = 1;
121         return;
122     }
123
124     strcat(client_log_buffer, line);
125     client_log_buffer_index += line_length;
126     client_log_buffer[client_log_buffer_index++] = '\n';
127 }
128
129 static void server_keylog_callback(const SSL *ssl, const char *line)
130 {
131     int line_length = strlen(line);
132
133     /* If the log doesn't fit, error out. */
134     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
135         TEST_info("Server log too full");
136         error_writing_log = 1;
137         return;
138     }
139
140     strcat(server_log_buffer, line);
141     server_log_buffer_index += line_length;
142     server_log_buffer[server_log_buffer_index++] = '\n';
143 }
144
145 static int compare_hex_encoded_buffer(const char *hex_encoded,
146                                       size_t hex_length,
147                                       const uint8_t *raw,
148                                       size_t raw_length)
149 {
150     size_t i, j;
151     char hexed[3];
152
153     if (!TEST_size_t_eq(raw_length * 2, hex_length))
154         return 1;
155
156     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
157         sprintf(hexed, "%02x", raw[i]);
158         if (!TEST_int_eq(hexed[0], hex_encoded[j])
159                 || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
160             return 1;
161     }
162
163     return 0;
164 }
165
166 static int test_keylog_output(char *buffer, const SSL *ssl,
167                               const SSL_SESSION *session,
168                               struct sslapitest_log_counts *expected)
169 {
170     char *token = NULL;
171     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0};
172     size_t client_random_size = SSL3_RANDOM_SIZE;
173     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
174     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
175     unsigned int rsa_key_exchange_count = 0;
176     unsigned int master_secret_count = 0;
177     unsigned int client_early_secret_count = 0;
178     unsigned int client_handshake_secret_count = 0;
179     unsigned int server_handshake_secret_count = 0;
180     unsigned int client_application_secret_count = 0;
181     unsigned int server_application_secret_count = 0;
182     unsigned int early_exporter_secret_count = 0;
183     unsigned int exporter_secret_count = 0;
184
185     for (token = strtok(buffer, " \n"); token != NULL;
186          token = strtok(NULL, " \n")) {
187         if (strcmp(token, "RSA") == 0) {
188             /*
189              * Premaster secret. Tokens should be: 16 ASCII bytes of
190              * hex-encoded encrypted secret, then the hex-encoded pre-master
191              * secret.
192              */
193             if (!TEST_ptr(token = strtok(NULL, " \n")))
194                 return 0;
195             if (!TEST_size_t_eq(strlen(token), 16))
196                 return 0;
197             if (!TEST_ptr(token = strtok(NULL, " \n")))
198                 return 0;
199             /*
200              * We can't sensibly check the log because the premaster secret is
201              * transient, and OpenSSL doesn't keep hold of it once the master
202              * secret is generated.
203              */
204             rsa_key_exchange_count++;
205         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
206             /*
207              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
208              * client random, then the hex-encoded master secret.
209              */
210             client_random_size = SSL_get_client_random(ssl,
211                                                        actual_client_random,
212                                                        SSL3_RANDOM_SIZE);
213             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
214                 return 0;
215
216             if (!TEST_ptr(token = strtok(NULL, " \n")))
217                 return 0;
218             if (!TEST_size_t_eq(strlen(token), 64))
219                 return 0;
220             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
221                                                        actual_client_random,
222                                                        client_random_size)))
223                 return 0;
224
225             if (!TEST_ptr(token = strtok(NULL, " \n")))
226                 return 0;
227             master_key_size = SSL_SESSION_get_master_key(session,
228                                                          actual_master_key,
229                                                          master_key_size);
230             if (!TEST_size_t_ne(master_key_size, 0))
231                 return 0;
232             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
233                                                        actual_master_key,
234                                                        master_key_size)))
235                 return 0;
236             master_secret_count++;
237         } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0
238                     || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
239                     || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
240                     || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
241                     || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0
242                     || strcmp(token, "EARLY_EXPORTER_SECRET") == 0
243                     || strcmp(token, "EXPORTER_SECRET") == 0) {
244             /*
245              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
246              * client random, and then the hex-encoded secret. In this case,
247              * we treat all of these secrets identically and then just
248              * distinguish between them when counting what we saw.
249              */
250             if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0)
251                 client_early_secret_count++;
252             else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
253                 client_handshake_secret_count++;
254             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
255                 server_handshake_secret_count++;
256             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
257                 client_application_secret_count++;
258             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
259                 server_application_secret_count++;
260             else if (strcmp(token, "EARLY_EXPORTER_SECRET") == 0)
261                 early_exporter_secret_count++;
262             else if (strcmp(token, "EXPORTER_SECRET") == 0)
263                 exporter_secret_count++;
264
265             client_random_size = SSL_get_client_random(ssl,
266                                                        actual_client_random,
267                                                        SSL3_RANDOM_SIZE);
268             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
269                 return 0;
270
271             if (!TEST_ptr(token = strtok(NULL, " \n")))
272                 return 0;
273             if (!TEST_size_t_eq(strlen(token), 64))
274                 return 0;
275             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
276                                                        actual_client_random,
277                                                        client_random_size)))
278                 return 0;
279
280             if (!TEST_ptr(token = strtok(NULL, " \n")))
281                 return 0;
282
283             /*
284              * TODO(TLS1.3): test that application traffic secrets are what
285              * we expect */
286         } else {
287             TEST_info("Unexpected token %s\n", token);
288             return 0;
289         }
290     }
291
292     /* Got what we expected? */
293     if (!TEST_size_t_eq(rsa_key_exchange_count,
294                         expected->rsa_key_exchange_count)
295             || !TEST_size_t_eq(master_secret_count,
296                                expected->master_secret_count)
297             || !TEST_size_t_eq(client_early_secret_count,
298                                expected->client_early_secret_count)
299             || !TEST_size_t_eq(client_handshake_secret_count,
300                                expected->client_handshake_secret_count)
301             || !TEST_size_t_eq(server_handshake_secret_count,
302                                expected->server_handshake_secret_count)
303             || !TEST_size_t_eq(client_application_secret_count,
304                                expected->client_application_secret_count)
305             || !TEST_size_t_eq(server_application_secret_count,
306                                expected->server_application_secret_count)
307             || !TEST_size_t_eq(early_exporter_secret_count,
308                                expected->early_exporter_secret_count)
309             || !TEST_size_t_eq(exporter_secret_count,
310                                expected->exporter_secret_count))
311         return 0;
312     return 1;
313 }
314
315 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
316 static int test_keylog(void)
317 {
318     SSL_CTX *cctx = NULL, *sctx = NULL;
319     SSL *clientssl = NULL, *serverssl = NULL;
320     int testresult = 0;
321     struct sslapitest_log_counts expected = {0};
322
323     /* Clean up logging space */
324     memset(client_log_buffer, 0, sizeof(client_log_buffer));
325     memset(server_log_buffer, 0, sizeof(server_log_buffer));
326     client_log_buffer_index = 0;
327     server_log_buffer_index = 0;
328     error_writing_log = 0;
329
330     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
331                                        TLS_client_method(),
332                                        TLS1_VERSION, TLS_MAX_VERSION,
333                                        &sctx, &cctx, cert, privkey)))
334         return 0;
335
336     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
337     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
338     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
339
340     /* We also want to ensure that we use RSA-based key exchange. */
341     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
342         goto end;
343
344     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
345             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
346         goto end;
347     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
348     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
349                    == client_keylog_callback))
350         goto end;
351     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
352     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
353                    == server_keylog_callback))
354         goto end;
355
356     /* Now do a handshake and check that the logs have been written to. */
357     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
358                                       &clientssl, NULL, NULL))
359             || !TEST_true(create_ssl_connection(serverssl, clientssl,
360                                                 SSL_ERROR_NONE))
361             || !TEST_false(error_writing_log)
362             || !TEST_int_gt(client_log_buffer_index, 0)
363             || !TEST_int_gt(server_log_buffer_index, 0))
364         goto end;
365
366     /*
367      * Now we want to test that our output data was vaguely sensible. We
368      * do that by using strtok and confirming that we have more or less the
369      * data we expect. For both client and server, we expect to see one master
370      * secret. The client should also see a RSA key exchange.
371      */
372     expected.rsa_key_exchange_count = 1;
373     expected.master_secret_count = 1;
374     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
375                                       SSL_get_session(clientssl), &expected)))
376         goto end;
377
378     expected.rsa_key_exchange_count = 0;
379     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
380                                       SSL_get_session(serverssl), &expected)))
381         goto end;
382
383     testresult = 1;
384
385 end:
386     SSL_free(serverssl);
387     SSL_free(clientssl);
388     SSL_CTX_free(sctx);
389     SSL_CTX_free(cctx);
390
391     return testresult;
392 }
393 #endif
394
395 #ifndef OPENSSL_NO_TLS1_3
396 static int test_keylog_no_master_key(void)
397 {
398     SSL_CTX *cctx = NULL, *sctx = NULL;
399     SSL *clientssl = NULL, *serverssl = NULL;
400     SSL_SESSION *sess = NULL;
401     int testresult = 0;
402     struct sslapitest_log_counts expected = {0};
403     unsigned char buf[1];
404     size_t readbytes, written;
405
406     /* Clean up logging space */
407     memset(client_log_buffer, 0, sizeof(client_log_buffer));
408     memset(server_log_buffer, 0, sizeof(server_log_buffer));
409     client_log_buffer_index = 0;
410     server_log_buffer_index = 0;
411     error_writing_log = 0;
412
413     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
414                                        TLS1_VERSION, TLS_MAX_VERSION,
415                                        &sctx, &cctx, cert, privkey))
416         || !TEST_true(SSL_CTX_set_max_early_data(sctx,
417                                                  SSL3_RT_MAX_PLAIN_LENGTH)))
418         return 0;
419
420     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
421             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
422         goto end;
423
424     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
425     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
426                    == client_keylog_callback))
427         goto end;
428
429     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
430     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
431                    == server_keylog_callback))
432         goto end;
433
434     /* Now do a handshake and check that the logs have been written to. */
435     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
436                                       &clientssl, NULL, NULL))
437             || !TEST_true(create_ssl_connection(serverssl, clientssl,
438                                                 SSL_ERROR_NONE))
439             || !TEST_false(error_writing_log))
440         goto end;
441
442     /*
443      * Now we want to test that our output data was vaguely sensible. For this
444      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
445      * TLSv1.3, but we do expect both client and server to emit keys.
446      */
447     expected.client_handshake_secret_count = 1;
448     expected.server_handshake_secret_count = 1;
449     expected.client_application_secret_count = 1;
450     expected.server_application_secret_count = 1;
451     expected.exporter_secret_count = 1;
452     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
453                                       SSL_get_session(clientssl), &expected))
454             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
455                                              SSL_get_session(serverssl),
456                                              &expected)))
457         goto end;
458
459     /* Terminate old session and resume with early data. */
460     sess = SSL_get1_session(clientssl);
461     SSL_shutdown(clientssl);
462     SSL_shutdown(serverssl);
463     SSL_free(serverssl);
464     SSL_free(clientssl);
465     serverssl = clientssl = NULL;
466
467     /* Reset key log */
468     memset(client_log_buffer, 0, sizeof(client_log_buffer));
469     memset(server_log_buffer, 0, sizeof(server_log_buffer));
470     client_log_buffer_index = 0;
471     server_log_buffer_index = 0;
472
473     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
474                                       &clientssl, NULL, NULL))
475             || !TEST_true(SSL_set_session(clientssl, sess))
476             /* Here writing 0 length early data is enough. */
477             || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
478             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
479                                                 &readbytes),
480                             SSL_READ_EARLY_DATA_ERROR)
481             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
482                             SSL_EARLY_DATA_ACCEPTED)
483             || !TEST_true(create_ssl_connection(serverssl, clientssl,
484                           SSL_ERROR_NONE))
485             || !TEST_true(SSL_session_reused(clientssl)))
486         goto end;
487
488     /* In addition to the previous entries, expect early secrets. */
489     expected.client_early_secret_count = 1;
490     expected.early_exporter_secret_count = 1;
491     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
492                                       SSL_get_session(clientssl), &expected))
493             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
494                                              SSL_get_session(serverssl),
495                                              &expected)))
496         goto end;
497
498     testresult = 1;
499
500 end:
501     SSL_SESSION_free(sess);
502     SSL_free(serverssl);
503     SSL_free(clientssl);
504     SSL_CTX_free(sctx);
505     SSL_CTX_free(cctx);
506
507     return testresult;
508 }
509 #endif
510
511 #ifndef OPENSSL_NO_TLS1_2
512 static int full_client_hello_callback(SSL *s, int *al, void *arg)
513 {
514     int *ctr = arg;
515     const unsigned char *p;
516     int *exts;
517     /* We only configure two ciphers, but the SCSV is added automatically. */
518 #ifdef OPENSSL_NO_EC
519     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0x00, 0xff};
520 #else
521     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
522                                               0x2c, 0x00, 0xff};
523 #endif
524     const int expected_extensions[] = {
525 #ifndef OPENSSL_NO_EC
526                                        11, 10,
527 #endif
528                                        35, 22, 23, 13};
529     size_t len;
530
531     /* Make sure we can defer processing and get called back. */
532     if ((*ctr)++ == 0)
533         return SSL_CLIENT_HELLO_RETRY;
534
535     len = SSL_client_hello_get0_ciphers(s, &p);
536     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
537             || !TEST_size_t_eq(
538                        SSL_client_hello_get0_compression_methods(s, &p), 1)
539             || !TEST_int_eq(*p, 0))
540         return SSL_CLIENT_HELLO_ERROR;
541     if (!SSL_client_hello_get1_extensions_present(s, &exts, &len))
542         return SSL_CLIENT_HELLO_ERROR;
543     if (len != OSSL_NELEM(expected_extensions) ||
544         memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
545         printf("ClientHello callback expected extensions mismatch\n");
546         OPENSSL_free(exts);
547         return SSL_CLIENT_HELLO_ERROR;
548     }
549     OPENSSL_free(exts);
550     return SSL_CLIENT_HELLO_SUCCESS;
551 }
552
553 static int test_client_hello_cb(void)
554 {
555     SSL_CTX *cctx = NULL, *sctx = NULL;
556     SSL *clientssl = NULL, *serverssl = NULL;
557     int testctr = 0, testresult = 0;
558
559     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
560                                        TLS1_VERSION, TLS_MAX_VERSION,
561                                        &sctx, &cctx, cert, privkey)))
562         goto end;
563     SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr);
564
565     /* The gimpy cipher list we configure can't do TLS 1.3. */
566     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
567
568     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
569                         "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
570             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
571                                              &clientssl, NULL, NULL))
572             || !TEST_false(create_ssl_connection(serverssl, clientssl,
573                         SSL_ERROR_WANT_CLIENT_HELLO_CB))
574                 /*
575                  * Passing a -1 literal is a hack since
576                  * the real value was lost.
577                  * */
578             || !TEST_int_eq(SSL_get_error(serverssl, -1),
579                             SSL_ERROR_WANT_CLIENT_HELLO_CB)
580             || !TEST_true(create_ssl_connection(serverssl, clientssl,
581                                                 SSL_ERROR_NONE)))
582         goto end;
583
584     testresult = 1;
585
586 end:
587     SSL_free(serverssl);
588     SSL_free(clientssl);
589     SSL_CTX_free(sctx);
590     SSL_CTX_free(cctx);
591
592     return testresult;
593 }
594
595 /*
596  * Very focused test to exercise a single case in the server-side state
597  * machine, when the ChangeCipherState message needs to actually change
598  * from one cipher to a different cipher (i.e., not changing from null
599  * encryption to real encryption).
600  */
601 static int test_ccs_change_cipher(void)
602 {
603     SSL_CTX *cctx = NULL, *sctx = NULL;
604     SSL *clientssl = NULL, *serverssl = NULL;
605     SSL_SESSION *sess = NULL, *sesspre, *sesspost;
606     int testresult = 0;
607     int i;
608     unsigned char buf;
609     size_t readbytes;
610
611     /*
612      * Create a conection so we can resume and potentially (but not) use
613      * a different cipher in the second connection.
614      */
615     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
616                                        TLS_client_method(),
617                                        TLS1_VERSION, TLS1_2_VERSION,
618                                        &sctx, &cctx, cert, privkey))
619             || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET))
620             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
621                           NULL, NULL))
622             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
623             || !TEST_true(create_ssl_connection(serverssl, clientssl,
624                                                 SSL_ERROR_NONE))
625             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
626             || !TEST_ptr(sess = SSL_get1_session(clientssl)))
627         goto end;
628
629     shutdown_ssl_connection(serverssl, clientssl);
630     serverssl = clientssl = NULL;
631
632     /* Resume, preferring a different cipher. Our server will force the
633      * same cipher to be used as the initial handshake. */
634     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
635                           NULL, NULL))
636             || !TEST_true(SSL_set_session(clientssl, sess))
637             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384:AES128-GCM-SHA256"))
638             || !TEST_true(create_ssl_connection(serverssl, clientssl,
639                                                 SSL_ERROR_NONE))
640             || !TEST_true(SSL_session_reused(clientssl))
641             || !TEST_true(SSL_session_reused(serverssl))
642             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
643             || !TEST_ptr_eq(sesspre, sesspost)
644             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
645                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
646         goto end;
647     shutdown_ssl_connection(serverssl, clientssl);
648     serverssl = clientssl = NULL;
649
650     /*
651      * Now create a fresh connection and try to renegotiate a different
652      * cipher on it.
653      */
654     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
655                                       NULL, NULL))
656             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
657             || !TEST_true(create_ssl_connection(serverssl, clientssl,
658                                                 SSL_ERROR_NONE))
659             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
660             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384"))
661             || !TEST_true(SSL_renegotiate(clientssl))
662             || !TEST_true(SSL_renegotiate_pending(clientssl)))
663         goto end;
664     /* Actually drive the renegotiation. */
665     for (i = 0; i < 3; i++) {
666         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
667             if (!TEST_ulong_eq(readbytes, 0))
668                 goto end;
669         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
670                                 SSL_ERROR_WANT_READ)) {
671             goto end;
672         }
673         if (SSL_read_ex(serverssl, &buf, sizeof(buf), &readbytes) > 0) {
674             if (!TEST_ulong_eq(readbytes, 0))
675                 goto end;
676         } else if (!TEST_int_eq(SSL_get_error(serverssl, 0),
677                                 SSL_ERROR_WANT_READ)) {
678             goto end;
679         }
680     }
681     /* sesspre and sesspost should be different since the cipher changed. */
682     if (!TEST_false(SSL_renegotiate_pending(clientssl))
683             || !TEST_false(SSL_session_reused(clientssl))
684             || !TEST_false(SSL_session_reused(serverssl))
685             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
686             || !TEST_ptr_ne(sesspre, sesspost)
687             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
688                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
689         goto end;
690
691     shutdown_ssl_connection(serverssl, clientssl);
692     serverssl = clientssl = NULL;
693
694     testresult = 1;
695
696 end:
697     SSL_free(serverssl);
698     SSL_free(clientssl);
699     SSL_CTX_free(sctx);
700     SSL_CTX_free(cctx);
701     SSL_SESSION_free(sess);
702
703     return testresult;
704 }
705 #endif
706
707 static int execute_test_large_message(const SSL_METHOD *smeth,
708                                       const SSL_METHOD *cmeth,
709                                       int min_version, int max_version,
710                                       int read_ahead)
711 {
712     SSL_CTX *cctx = NULL, *sctx = NULL;
713     SSL *clientssl = NULL, *serverssl = NULL;
714     int testresult = 0;
715     int i;
716     BIO *certbio = NULL;
717     X509 *chaincert = NULL;
718     int certlen;
719
720     if (!TEST_ptr(certbio = BIO_new_file(cert, "r")))
721         goto end;
722     chaincert = PEM_read_bio_X509(certbio, NULL, NULL, NULL);
723     BIO_free(certbio);
724     certbio = NULL;
725     if (!TEST_ptr(chaincert))
726         goto end;
727
728     if (!TEST_true(create_ssl_ctx_pair(smeth, cmeth, min_version, max_version,
729                                        &sctx, &cctx, cert, privkey)))
730         goto end;
731
732     if (read_ahead) {
733         /*
734          * Test that read_ahead works correctly when dealing with large
735          * records
736          */
737         SSL_CTX_set_read_ahead(cctx, 1);
738     }
739
740     /*
741      * We assume the supplied certificate is big enough so that if we add
742      * NUM_EXTRA_CERTS it will make the overall message large enough. The
743      * default buffer size is requested to be 16k, but due to the way BUF_MEM
744      * works, it ends up allocating a little over 21k (16 * 4/3). So, in this
745      * test we need to have a message larger than that.
746      */
747     certlen = i2d_X509(chaincert, NULL);
748     OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
749                    (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
750     for (i = 0; i < NUM_EXTRA_CERTS; i++) {
751         if (!X509_up_ref(chaincert))
752             goto end;
753         if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
754             X509_free(chaincert);
755             goto end;
756         }
757     }
758
759     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
760                                       NULL, NULL))
761             || !TEST_true(create_ssl_connection(serverssl, clientssl,
762                                                 SSL_ERROR_NONE)))
763         goto end;
764
765     /*
766      * Calling SSL_clear() first is not required but this tests that SSL_clear()
767      * doesn't leak (when using enable-crypto-mdebug).
768      */
769     if (!TEST_true(SSL_clear(serverssl)))
770         goto end;
771
772     testresult = 1;
773  end:
774     X509_free(chaincert);
775     SSL_free(serverssl);
776     SSL_free(clientssl);
777     SSL_CTX_free(sctx);
778     SSL_CTX_free(cctx);
779
780     return testresult;
781 }
782
783 static int test_large_message_tls(void)
784 {
785     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
786                                       TLS1_VERSION, TLS_MAX_VERSION,
787                                       0);
788 }
789
790 static int test_large_message_tls_read_ahead(void)
791 {
792     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
793                                       TLS1_VERSION, TLS_MAX_VERSION,
794                                       1);
795 }
796
797 #ifndef OPENSSL_NO_DTLS
798 static int test_large_message_dtls(void)
799 {
800     /*
801      * read_ahead is not relevant to DTLS because DTLS always acts as if
802      * read_ahead is set.
803      */
804     return execute_test_large_message(DTLS_server_method(),
805                                       DTLS_client_method(),
806                                       DTLS1_VERSION, DTLS_MAX_VERSION,
807                                       0);
808 }
809 #endif
810
811 #ifndef OPENSSL_NO_OCSP
812 static int ocsp_server_cb(SSL *s, void *arg)
813 {
814     int *argi = (int *)arg;
815     unsigned char *copy = NULL;
816     STACK_OF(OCSP_RESPID) *ids = NULL;
817     OCSP_RESPID *id = NULL;
818
819     if (*argi == 2) {
820         /* In this test we are expecting exactly 1 OCSP_RESPID */
821         SSL_get_tlsext_status_ids(s, &ids);
822         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
823             return SSL_TLSEXT_ERR_ALERT_FATAL;
824
825         id = sk_OCSP_RESPID_value(ids, 0);
826         if (id == NULL || !OCSP_RESPID_match(id, ocspcert))
827             return SSL_TLSEXT_ERR_ALERT_FATAL;
828     } else if (*argi != 1) {
829         return SSL_TLSEXT_ERR_ALERT_FATAL;
830     }
831
832     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
833         return SSL_TLSEXT_ERR_ALERT_FATAL;
834
835     SSL_set_tlsext_status_ocsp_resp(s, copy, sizeof(orespder));
836     ocsp_server_called = 1;
837     return SSL_TLSEXT_ERR_OK;
838 }
839
840 static int ocsp_client_cb(SSL *s, void *arg)
841 {
842     int *argi = (int *)arg;
843     const unsigned char *respderin;
844     size_t len;
845
846     if (*argi != 1 && *argi != 2)
847         return 0;
848
849     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
850     if (!TEST_mem_eq(orespder, len, respderin, len))
851         return 0;
852
853     ocsp_client_called = 1;
854     return 1;
855 }
856
857 static int test_tlsext_status_type(void)
858 {
859     SSL_CTX *cctx = NULL, *sctx = NULL;
860     SSL *clientssl = NULL, *serverssl = NULL;
861     int testresult = 0;
862     STACK_OF(OCSP_RESPID) *ids = NULL;
863     OCSP_RESPID *id = NULL;
864     BIO *certbio = NULL;
865
866     if (!create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
867                              TLS1_VERSION, TLS_MAX_VERSION,
868                              &sctx, &cctx, cert, privkey))
869         return 0;
870
871     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
872         goto end;
873
874     /* First just do various checks getting and setting tlsext_status_type */
875
876     clientssl = SSL_new(cctx);
877     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
878             || !TEST_true(SSL_set_tlsext_status_type(clientssl,
879                                                       TLSEXT_STATUSTYPE_ocsp))
880             || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
881                             TLSEXT_STATUSTYPE_ocsp))
882         goto end;
883
884     SSL_free(clientssl);
885     clientssl = NULL;
886
887     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
888      || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
889         goto end;
890
891     clientssl = SSL_new(cctx);
892     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
893         goto end;
894     SSL_free(clientssl);
895     clientssl = NULL;
896
897     /*
898      * Now actually do a handshake and check OCSP information is exchanged and
899      * the callbacks get called
900      */
901     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
902     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
903     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
904     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
905     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
906                                       &clientssl, NULL, NULL))
907             || !TEST_true(create_ssl_connection(serverssl, clientssl,
908                                                 SSL_ERROR_NONE))
909             || !TEST_true(ocsp_client_called)
910             || !TEST_true(ocsp_server_called))
911         goto end;
912     SSL_free(serverssl);
913     SSL_free(clientssl);
914     serverssl = NULL;
915     clientssl = NULL;
916
917     /* Try again but this time force the server side callback to fail */
918     ocsp_client_called = 0;
919     ocsp_server_called = 0;
920     cdummyarg = 0;
921     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
922                                       &clientssl, NULL, NULL))
923                 /* This should fail because the callback will fail */
924             || !TEST_false(create_ssl_connection(serverssl, clientssl,
925                                                  SSL_ERROR_NONE))
926             || !TEST_false(ocsp_client_called)
927             || !TEST_false(ocsp_server_called))
928         goto end;
929     SSL_free(serverssl);
930     SSL_free(clientssl);
931     serverssl = NULL;
932     clientssl = NULL;
933
934     /*
935      * This time we'll get the client to send an OCSP_RESPID that it will
936      * accept.
937      */
938     ocsp_client_called = 0;
939     ocsp_server_called = 0;
940     cdummyarg = 2;
941     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
942                                       &clientssl, NULL, NULL)))
943         goto end;
944
945     /*
946      * We'll just use any old cert for this test - it doesn't have to be an OCSP
947      * specific one. We'll use the server cert.
948      */
949     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
950             || !TEST_ptr(id = OCSP_RESPID_new())
951             || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
952             || !TEST_ptr(ocspcert = PEM_read_bio_X509(certbio,
953                                                       NULL, NULL, NULL))
954             || !TEST_true(OCSP_RESPID_set_by_key(id, ocspcert))
955             || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
956         goto end;
957     id = NULL;
958     SSL_set_tlsext_status_ids(clientssl, ids);
959     /* Control has been transferred */
960     ids = NULL;
961
962     BIO_free(certbio);
963     certbio = NULL;
964
965     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
966                                          SSL_ERROR_NONE))
967             || !TEST_true(ocsp_client_called)
968             || !TEST_true(ocsp_server_called))
969         goto end;
970
971     testresult = 1;
972
973  end:
974     SSL_free(serverssl);
975     SSL_free(clientssl);
976     SSL_CTX_free(sctx);
977     SSL_CTX_free(cctx);
978     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
979     OCSP_RESPID_free(id);
980     BIO_free(certbio);
981     X509_free(ocspcert);
982     ocspcert = NULL;
983
984     return testresult;
985 }
986 #endif
987
988 #if !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
989 static int new_called, remove_called, get_called;
990
991 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
992 {
993     new_called++;
994     /*
995      * sess has been up-refed for us, but we don't actually need it so free it
996      * immediately.
997      */
998     SSL_SESSION_free(sess);
999     return 1;
1000 }
1001
1002 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
1003 {
1004     remove_called++;
1005 }
1006
1007 static SSL_SESSION *get_sess_val = NULL;
1008
1009 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
1010                                    int *copy)
1011 {
1012     get_called++;
1013     *copy = 1;
1014     return get_sess_val;
1015 }
1016
1017 static int execute_test_session(int maxprot, int use_int_cache,
1018                                 int use_ext_cache)
1019 {
1020     SSL_CTX *sctx = NULL, *cctx = NULL;
1021     SSL *serverssl1 = NULL, *clientssl1 = NULL;
1022     SSL *serverssl2 = NULL, *clientssl2 = NULL;
1023 # ifndef OPENSSL_NO_TLS1_1
1024     SSL *serverssl3 = NULL, *clientssl3 = NULL;
1025 # endif
1026     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
1027     int testresult = 0, numnewsesstick = 1;
1028
1029     new_called = remove_called = 0;
1030
1031     /* TLSv1.3 sends 2 NewSessionTickets */
1032     if (maxprot == TLS1_3_VERSION)
1033         numnewsesstick = 2;
1034
1035     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1036                                        TLS1_VERSION, TLS_MAX_VERSION,
1037                                        &sctx, &cctx, cert, privkey)))
1038         return 0;
1039
1040     /*
1041      * Only allow the max protocol version so we can force a connection failure
1042      * later
1043      */
1044     SSL_CTX_set_min_proto_version(cctx, maxprot);
1045     SSL_CTX_set_max_proto_version(cctx, maxprot);
1046
1047     /* Set up session cache */
1048     if (use_ext_cache) {
1049         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
1050         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
1051     }
1052     if (use_int_cache) {
1053         /* Also covers instance where both are set */
1054         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
1055     } else {
1056         SSL_CTX_set_session_cache_mode(cctx,
1057                                        SSL_SESS_CACHE_CLIENT
1058                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1059     }
1060
1061     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
1062                                       NULL, NULL))
1063             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
1064                                                 SSL_ERROR_NONE))
1065             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
1066         goto end;
1067
1068     /* Should fail because it should already be in the cache */
1069     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
1070         goto end;
1071     if (use_ext_cache
1072             && (!TEST_int_eq(new_called, numnewsesstick)
1073
1074                 || !TEST_int_eq(remove_called, 0)))
1075         goto end;
1076
1077     new_called = remove_called = 0;
1078     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1079                                       &clientssl2, NULL, NULL))
1080             || !TEST_true(SSL_set_session(clientssl2, sess1))
1081             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1082                                                 SSL_ERROR_NONE))
1083             || !TEST_true(SSL_session_reused(clientssl2)))
1084         goto end;
1085
1086     if (maxprot == TLS1_3_VERSION) {
1087         /*
1088          * In TLSv1.3 we should have created a new session even though we have
1089          * resumed. Since we attempted a resume we should also have removed the
1090          * old ticket from the cache so that we try to only use tickets once.
1091          */
1092         if (use_ext_cache
1093                 && (!TEST_int_eq(new_called, 1)
1094                     || !TEST_int_eq(remove_called, 1)))
1095             goto end;
1096     } else {
1097         /*
1098          * In TLSv1.2 we expect to have resumed so no sessions added or
1099          * removed.
1100          */
1101         if (use_ext_cache
1102                 && (!TEST_int_eq(new_called, 0)
1103                     || !TEST_int_eq(remove_called, 0)))
1104             goto end;
1105     }
1106
1107     SSL_SESSION_free(sess1);
1108     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
1109         goto end;
1110     shutdown_ssl_connection(serverssl2, clientssl2);
1111     serverssl2 = clientssl2 = NULL;
1112
1113     new_called = remove_called = 0;
1114     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1115                                       &clientssl2, NULL, NULL))
1116             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1117                                                 SSL_ERROR_NONE)))
1118         goto end;
1119
1120     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
1121         goto end;
1122
1123     if (use_ext_cache
1124             && (!TEST_int_eq(new_called, numnewsesstick)
1125                 || !TEST_int_eq(remove_called, 0)))
1126         goto end;
1127
1128     new_called = remove_called = 0;
1129     /*
1130      * This should clear sess2 from the cache because it is a "bad" session.
1131      * See SSL_set_session() documentation.
1132      */
1133     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
1134         goto end;
1135     if (use_ext_cache
1136             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1137         goto end;
1138     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
1139         goto end;
1140
1141     if (use_int_cache) {
1142         /* Should succeeded because it should not already be in the cache */
1143         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
1144                 || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
1145             goto end;
1146     }
1147
1148     new_called = remove_called = 0;
1149     /* This shouldn't be in the cache so should fail */
1150     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
1151         goto end;
1152
1153     if (use_ext_cache
1154             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1155         goto end;
1156
1157 # if !defined(OPENSSL_NO_TLS1_1)
1158     new_called = remove_called = 0;
1159     /* Force a connection failure */
1160     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
1161     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
1162                                       &clientssl3, NULL, NULL))
1163             || !TEST_true(SSL_set_session(clientssl3, sess1))
1164             /* This should fail because of the mismatched protocol versions */
1165             || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
1166                                                  SSL_ERROR_NONE)))
1167         goto end;
1168
1169     /* We should have automatically removed the session from the cache */
1170     if (use_ext_cache
1171             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1172         goto end;
1173
1174     /* Should succeed because it should not already be in the cache */
1175     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
1176         goto end;
1177 # endif
1178
1179     /* Now do some tests for server side caching */
1180     if (use_ext_cache) {
1181         SSL_CTX_sess_set_new_cb(cctx, NULL);
1182         SSL_CTX_sess_set_remove_cb(cctx, NULL);
1183         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
1184         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
1185         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
1186         get_sess_val = NULL;
1187     }
1188
1189     SSL_CTX_set_session_cache_mode(cctx, 0);
1190     /* Internal caching is the default on the server side */
1191     if (!use_int_cache)
1192         SSL_CTX_set_session_cache_mode(sctx,
1193                                        SSL_SESS_CACHE_SERVER
1194                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1195
1196     SSL_free(serverssl1);
1197     SSL_free(clientssl1);
1198     serverssl1 = clientssl1 = NULL;
1199     SSL_free(serverssl2);
1200     SSL_free(clientssl2);
1201     serverssl2 = clientssl2 = NULL;
1202     SSL_SESSION_free(sess1);
1203     sess1 = NULL;
1204     SSL_SESSION_free(sess2);
1205     sess2 = NULL;
1206
1207     SSL_CTX_set_max_proto_version(sctx, maxprot);
1208     if (maxprot == TLS1_2_VERSION)
1209         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
1210     new_called = remove_called = get_called = 0;
1211     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
1212                                       NULL, NULL))
1213             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
1214                                                 SSL_ERROR_NONE))
1215             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
1216             || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
1217         goto end;
1218
1219     if (use_int_cache) {
1220         if (maxprot == TLS1_3_VERSION && !use_ext_cache) {
1221             /*
1222              * In TLSv1.3 it should not have been added to the internal cache,
1223              * except in the case where we also have an external cache (in that
1224              * case it gets added to the cache in order to generate remove
1225              * events after timeout).
1226              */
1227             if (!TEST_false(SSL_CTX_remove_session(sctx, sess2)))
1228                 goto end;
1229         } else {
1230             /* Should fail because it should already be in the cache */
1231             if (!TEST_false(SSL_CTX_add_session(sctx, sess2)))
1232                 goto end;
1233         }
1234     }
1235
1236     if (use_ext_cache) {
1237         SSL_SESSION *tmp = sess2;
1238
1239         if (!TEST_int_eq(new_called, numnewsesstick)
1240                 || !TEST_int_eq(remove_called, 0)
1241                 || !TEST_int_eq(get_called, 0))
1242             goto end;
1243         /*
1244          * Delete the session from the internal cache to force a lookup from
1245          * the external cache. We take a copy first because
1246          * SSL_CTX_remove_session() also marks the session as non-resumable.
1247          */
1248         if (use_int_cache && maxprot != TLS1_3_VERSION) {
1249             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
1250                     || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
1251                 goto end;
1252             SSL_SESSION_free(sess2);
1253         }
1254         sess2 = tmp;
1255     }
1256
1257     new_called = remove_called = get_called = 0;
1258     get_sess_val = sess2;
1259     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1260                                       &clientssl2, NULL, NULL))
1261             || !TEST_true(SSL_set_session(clientssl2, sess1))
1262             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1263                                                 SSL_ERROR_NONE))
1264             || !TEST_true(SSL_session_reused(clientssl2)))
1265         goto end;
1266
1267     if (use_ext_cache) {
1268         if (!TEST_int_eq(remove_called, 0))
1269             goto end;
1270
1271         if (maxprot == TLS1_3_VERSION) {
1272             if (!TEST_int_eq(new_called, 1)
1273                     || !TEST_int_eq(get_called, 0))
1274                 goto end;
1275         } else {
1276             if (!TEST_int_eq(new_called, 0)
1277                     || !TEST_int_eq(get_called, 1))
1278                 goto end;
1279         }
1280     }
1281
1282     testresult = 1;
1283
1284  end:
1285     SSL_free(serverssl1);
1286     SSL_free(clientssl1);
1287     SSL_free(serverssl2);
1288     SSL_free(clientssl2);
1289 # ifndef OPENSSL_NO_TLS1_1
1290     SSL_free(serverssl3);
1291     SSL_free(clientssl3);
1292 # endif
1293     SSL_SESSION_free(sess1);
1294     SSL_SESSION_free(sess2);
1295     SSL_CTX_free(sctx);
1296     SSL_CTX_free(cctx);
1297
1298     return testresult;
1299 }
1300 #endif /* !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
1301
1302 static int test_session_with_only_int_cache(void)
1303 {
1304 #ifndef OPENSSL_NO_TLS1_3
1305     if (!execute_test_session(TLS1_3_VERSION, 1, 0))
1306         return 0;
1307 #endif
1308
1309 #ifndef OPENSSL_NO_TLS1_2
1310     return execute_test_session(TLS1_2_VERSION, 1, 0);
1311 #else
1312     return 1;
1313 #endif
1314 }
1315
1316 static int test_session_with_only_ext_cache(void)
1317 {
1318 #ifndef OPENSSL_NO_TLS1_3
1319     if (!execute_test_session(TLS1_3_VERSION, 0, 1))
1320         return 0;
1321 #endif
1322
1323 #ifndef OPENSSL_NO_TLS1_2
1324     return execute_test_session(TLS1_2_VERSION, 0, 1);
1325 #else
1326     return 1;
1327 #endif
1328 }
1329
1330 static int test_session_with_both_cache(void)
1331 {
1332 #ifndef OPENSSL_NO_TLS1_3
1333     if (!execute_test_session(TLS1_3_VERSION, 1, 1))
1334         return 0;
1335 #endif
1336
1337 #ifndef OPENSSL_NO_TLS1_2
1338     return execute_test_session(TLS1_2_VERSION, 1, 1);
1339 #else
1340     return 1;
1341 #endif
1342 }
1343
1344 #ifndef OPENSSL_NO_TLS1_3
1345 static SSL_SESSION *sesscache[6];
1346 static int do_cache;
1347
1348 static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
1349 {
1350     if (do_cache) {
1351         sesscache[new_called] = sess;
1352     } else {
1353         /* We don't need the reference to the session, so free it */
1354         SSL_SESSION_free(sess);
1355     }
1356     new_called++;
1357
1358     return 1;
1359 }
1360
1361 static int post_handshake_verify(SSL *sssl, SSL *cssl)
1362 {
1363     SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
1364     if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
1365         return 0;
1366
1367     /* Start handshake on the server and client */
1368     if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
1369             || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
1370             || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
1371             || !TEST_true(create_ssl_connection(sssl, cssl,
1372                                                 SSL_ERROR_NONE)))
1373         return 0;
1374
1375     return 1;
1376 }
1377
1378 static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx,
1379                              SSL_CTX **cctx)
1380 {
1381     int sess_id_ctx = 1;
1382
1383     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1384                                        TLS1_VERSION, TLS_MAX_VERSION, sctx,
1385                                        cctx, cert, privkey))
1386             || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx))
1387             || !TEST_true(SSL_CTX_set_session_id_context(*sctx,
1388                                                          (void *)&sess_id_ctx,
1389                                                          sizeof(sess_id_ctx))))
1390         return 0;
1391
1392     if (stateful)
1393         SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET);
1394
1395     SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT
1396                                           | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1397     SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb);
1398
1399     return 1;
1400 }
1401
1402 static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ)
1403 {
1404     SSL *serverssl = NULL, *clientssl = NULL;
1405     int i;
1406
1407     /* Test that we can resume with all the tickets we got given */
1408     for (i = 0; i < idx * 2; i++) {
1409         new_called = 0;
1410         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1411                                               &clientssl, NULL, NULL))
1412                 || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
1413             goto end;
1414
1415         SSL_set_post_handshake_auth(clientssl, 1);
1416
1417         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1418                                                     SSL_ERROR_NONE)))
1419             goto end;
1420
1421         /*
1422          * Following a successful resumption we only get 1 ticket. After a
1423          * failed one we should get idx tickets.
1424          */
1425         if (succ) {
1426             if (!TEST_true(SSL_session_reused(clientssl))
1427                     || !TEST_int_eq(new_called, 1))
1428                 goto end;
1429         } else {
1430             if (!TEST_false(SSL_session_reused(clientssl))
1431                     || !TEST_int_eq(new_called, idx))
1432                 goto end;
1433         }
1434
1435         new_called = 0;
1436         /* After a post-handshake authentication we should get 1 new ticket */
1437         if (succ
1438                 && (!post_handshake_verify(serverssl, clientssl)
1439                     || !TEST_int_eq(new_called, 1)))
1440             goto end;
1441
1442         SSL_shutdown(clientssl);
1443         SSL_shutdown(serverssl);
1444         SSL_free(serverssl);
1445         SSL_free(clientssl);
1446         serverssl = clientssl = NULL;
1447         SSL_SESSION_free(sesscache[i]);
1448         sesscache[i] = NULL;
1449     }
1450
1451     return 1;
1452
1453  end:
1454     SSL_free(clientssl);
1455     SSL_free(serverssl);
1456     return 0;
1457 }
1458
1459 static int test_tickets(int stateful, int idx)
1460 {
1461     SSL_CTX *sctx = NULL, *cctx = NULL;
1462     SSL *serverssl = NULL, *clientssl = NULL;
1463     int testresult = 0;
1464     size_t j;
1465
1466     /* idx is the test number, but also the number of tickets we want */
1467
1468     new_called = 0;
1469     do_cache = 1;
1470
1471     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
1472         goto end;
1473
1474     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1475                                           &clientssl, NULL, NULL)))
1476         goto end;
1477
1478     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1479                                                 SSL_ERROR_NONE))
1480                /* Check we got the number of tickets we were expecting */
1481             || !TEST_int_eq(idx, new_called))
1482         goto end;
1483
1484     SSL_shutdown(clientssl);
1485     SSL_shutdown(serverssl);
1486     SSL_free(serverssl);
1487     SSL_free(clientssl);
1488     SSL_CTX_free(sctx);
1489     SSL_CTX_free(cctx);
1490     clientssl = serverssl = NULL;
1491     sctx = cctx = NULL;
1492
1493     /*
1494      * Now we try to resume with the tickets we previously created. The
1495      * resumption attempt is expected to fail (because we're now using a new
1496      * SSL_CTX). We should see idx number of tickets issued again.
1497      */
1498
1499     /* Stop caching sessions - just count them */
1500     do_cache = 0;
1501
1502     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
1503         goto end;
1504
1505     if (!check_resumption(idx, sctx, cctx, 0))
1506         goto end;
1507
1508     /* Start again with caching sessions */
1509     new_called = 0;
1510     do_cache = 1;
1511     SSL_CTX_free(sctx);
1512     SSL_CTX_free(cctx);
1513     sctx = cctx = NULL;
1514
1515     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
1516         goto end;
1517
1518     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1519                                           &clientssl, NULL, NULL)))
1520         goto end;
1521
1522     SSL_set_post_handshake_auth(clientssl, 1);
1523
1524     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1525                                                 SSL_ERROR_NONE))
1526                /* Check we got the number of tickets we were expecting */
1527             || !TEST_int_eq(idx, new_called))
1528         goto end;
1529
1530     /* After a post-handshake authentication we should get new tickets issued */
1531     if (!post_handshake_verify(serverssl, clientssl)
1532             || !TEST_int_eq(idx * 2, new_called))
1533         goto end;
1534
1535     SSL_shutdown(clientssl);
1536     SSL_shutdown(serverssl);
1537     SSL_free(serverssl);
1538     SSL_free(clientssl);
1539     serverssl = clientssl = NULL;
1540
1541     /* Stop caching sessions - just count them */
1542     do_cache = 0;
1543
1544     /*
1545      * Check we can resume with all the tickets we created. This time around the
1546      * resumptions should all be successful.
1547      */
1548     if (!check_resumption(idx, sctx, cctx, 1))
1549         goto end;
1550
1551     testresult = 1;
1552
1553  end:
1554     SSL_free(serverssl);
1555     SSL_free(clientssl);
1556     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
1557         SSL_SESSION_free(sesscache[j]);
1558         sesscache[j] = NULL;
1559     }
1560     SSL_CTX_free(sctx);
1561     SSL_CTX_free(cctx);
1562
1563     return testresult;
1564 }
1565
1566 static int test_stateless_tickets(int idx)
1567 {
1568     return test_tickets(0, idx);
1569 }
1570
1571 static int test_stateful_tickets(int idx)
1572 {
1573     return test_tickets(1, idx);
1574 }
1575
1576 static int test_psk_tickets(void)
1577 {
1578     SSL_CTX *sctx = NULL, *cctx = NULL;
1579     SSL *serverssl = NULL, *clientssl = NULL;
1580     int testresult = 0;
1581     int sess_id_ctx = 1;
1582
1583     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1584                                        TLS1_VERSION, TLS_MAX_VERSION, &sctx,
1585                                        &cctx, NULL, NULL))
1586             || !TEST_true(SSL_CTX_set_session_id_context(sctx,
1587                                                          (void *)&sess_id_ctx,
1588                                                          sizeof(sess_id_ctx))))
1589         goto end;
1590
1591     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
1592                                          | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1593     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
1594     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
1595     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
1596     use_session_cb_cnt = 0;
1597     find_session_cb_cnt = 0;
1598     srvid = pskid;
1599     new_called = 0;
1600
1601     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1602                                       NULL, NULL)))
1603         goto end;
1604     clientpsk = serverpsk = create_a_psk(clientssl);
1605     if (!TEST_ptr(clientpsk))
1606         goto end;
1607     SSL_SESSION_up_ref(clientpsk);
1608
1609     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1610                                                 SSL_ERROR_NONE))
1611             || !TEST_int_eq(1, find_session_cb_cnt)
1612             || !TEST_int_eq(1, use_session_cb_cnt)
1613                /* We should always get 1 ticket when using external PSK */
1614             || !TEST_int_eq(1, new_called))
1615         goto end;
1616
1617     testresult = 1;
1618
1619  end:
1620     SSL_free(serverssl);
1621     SSL_free(clientssl);
1622     SSL_CTX_free(sctx);
1623     SSL_CTX_free(cctx);
1624     SSL_SESSION_free(clientpsk);
1625     SSL_SESSION_free(serverpsk);
1626     clientpsk = serverpsk = NULL;
1627
1628     return testresult;
1629 }
1630 #endif
1631
1632 #define USE_NULL            0
1633 #define USE_BIO_1           1
1634 #define USE_BIO_2           2
1635 #define USE_DEFAULT         3
1636
1637 #define CONNTYPE_CONNECTION_SUCCESS  0
1638 #define CONNTYPE_CONNECTION_FAIL     1
1639 #define CONNTYPE_NO_CONNECTION       2
1640
1641 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
1642 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
1643 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
1644 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
1645 #else
1646 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
1647 #endif
1648
1649 #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
1650                                 + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
1651                                 + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
1652
1653 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
1654 {
1655     switch (type) {
1656     case USE_NULL:
1657         *res = NULL;
1658         break;
1659     case USE_BIO_1:
1660         *res = bio1;
1661         break;
1662     case USE_BIO_2:
1663         *res = bio2;
1664         break;
1665     }
1666 }
1667
1668
1669 /*
1670  * Tests calls to SSL_set_bio() under various conditions.
1671  *
1672  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
1673  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
1674  * then do more tests where we create a successful connection first using our
1675  * standard connection setup functions, and then call SSL_set_bio() with
1676  * various combinations of valid BIOs or NULL. We then repeat these tests
1677  * following a failed connection. In this last case we are looking to check that
1678  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
1679  */
1680 static int test_ssl_set_bio(int idx)
1681 {
1682     SSL_CTX *sctx = NULL, *cctx = NULL;
1683     BIO *bio1 = NULL;
1684     BIO *bio2 = NULL;
1685     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
1686     SSL *serverssl = NULL, *clientssl = NULL;
1687     int initrbio, initwbio, newrbio, newwbio, conntype;
1688     int testresult = 0;
1689
1690     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
1691         initrbio = idx % 3;
1692         idx /= 3;
1693         initwbio = idx % 3;
1694         idx /= 3;
1695         newrbio = idx % 3;
1696         idx /= 3;
1697         newwbio = idx % 3;
1698         conntype = CONNTYPE_NO_CONNECTION;
1699     } else {
1700         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
1701         initrbio = initwbio = USE_DEFAULT;
1702         newrbio = idx % 2;
1703         idx /= 2;
1704         newwbio = idx % 2;
1705         idx /= 2;
1706         conntype = idx % 2;
1707     }
1708
1709     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1710                                        TLS1_VERSION, TLS_MAX_VERSION,
1711                                        &sctx, &cctx, cert, privkey)))
1712         goto end;
1713
1714     if (conntype == CONNTYPE_CONNECTION_FAIL) {
1715         /*
1716          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
1717          * because we reduced the number of tests in the definition of
1718          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
1719          * mismatched protocol versions we will force a connection failure.
1720          */
1721         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
1722         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1723     }
1724
1725     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1726                                       NULL, NULL)))
1727         goto end;
1728
1729     if (initrbio == USE_BIO_1
1730             || initwbio == USE_BIO_1
1731             || newrbio == USE_BIO_1
1732             || newwbio == USE_BIO_1) {
1733         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
1734             goto end;
1735     }
1736
1737     if (initrbio == USE_BIO_2
1738             || initwbio == USE_BIO_2
1739             || newrbio == USE_BIO_2
1740             || newwbio == USE_BIO_2) {
1741         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
1742             goto end;
1743     }
1744
1745     if (initrbio != USE_DEFAULT) {
1746         setupbio(&irbio, bio1, bio2, initrbio);
1747         setupbio(&iwbio, bio1, bio2, initwbio);
1748         SSL_set_bio(clientssl, irbio, iwbio);
1749
1750         /*
1751          * We want to maintain our own refs to these BIO, so do an up ref for
1752          * each BIO that will have ownership transferred in the SSL_set_bio()
1753          * call
1754          */
1755         if (irbio != NULL)
1756             BIO_up_ref(irbio);
1757         if (iwbio != NULL && iwbio != irbio)
1758             BIO_up_ref(iwbio);
1759     }
1760
1761     if (conntype != CONNTYPE_NO_CONNECTION
1762             && !TEST_true(create_ssl_connection(serverssl, clientssl,
1763                                                 SSL_ERROR_NONE)
1764                           == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
1765         goto end;
1766
1767     setupbio(&nrbio, bio1, bio2, newrbio);
1768     setupbio(&nwbio, bio1, bio2, newwbio);
1769
1770     /*
1771      * We will (maybe) transfer ownership again so do more up refs.
1772      * SSL_set_bio() has some really complicated ownership rules where BIOs have
1773      * already been set!
1774      */
1775     if (nrbio != NULL
1776             && nrbio != irbio
1777             && (nwbio != iwbio || nrbio != nwbio))
1778         BIO_up_ref(nrbio);
1779     if (nwbio != NULL
1780             && nwbio != nrbio
1781             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
1782         BIO_up_ref(nwbio);
1783
1784     SSL_set_bio(clientssl, nrbio, nwbio);
1785
1786     testresult = 1;
1787
1788  end:
1789     BIO_free(bio1);
1790     BIO_free(bio2);
1791
1792     /*
1793      * This test is checking that the ref counting for SSL_set_bio is correct.
1794      * If we get here and we did too many frees then we will fail in the above
1795      * functions. If we haven't done enough then this will only be detected in
1796      * a crypto-mdebug build
1797      */
1798     SSL_free(serverssl);
1799     SSL_free(clientssl);
1800     SSL_CTX_free(sctx);
1801     SSL_CTX_free(cctx);
1802     return testresult;
1803 }
1804
1805 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
1806
1807 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
1808 {
1809     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
1810     SSL_CTX *ctx;
1811     SSL *ssl = NULL;
1812     int testresult = 0;
1813
1814     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
1815             || !TEST_ptr(ssl = SSL_new(ctx))
1816             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
1817             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
1818         goto end;
1819
1820     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
1821
1822     /*
1823      * If anything goes wrong here then we could leak memory, so this will
1824      * be caught in a crypto-mdebug build
1825      */
1826     BIO_push(sslbio, membio1);
1827
1828     /* Verify changing the rbio/wbio directly does not cause leaks */
1829     if (change_bio != NO_BIO_CHANGE) {
1830         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem()))) {
1831             ssl = NULL;
1832             goto end;
1833         }
1834         if (change_bio == CHANGE_RBIO)
1835             SSL_set0_rbio(ssl, membio2);
1836         else
1837             SSL_set0_wbio(ssl, membio2);
1838     }
1839     ssl = NULL;
1840
1841     if (pop_ssl)
1842         BIO_pop(sslbio);
1843     else
1844         BIO_pop(membio1);
1845
1846     testresult = 1;
1847  end:
1848     BIO_free(membio1);
1849     BIO_free(sslbio);
1850     SSL_free(ssl);
1851     SSL_CTX_free(ctx);
1852
1853     return testresult;
1854 }
1855
1856 static int test_ssl_bio_pop_next_bio(void)
1857 {
1858     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
1859 }
1860
1861 static int test_ssl_bio_pop_ssl_bio(void)
1862 {
1863     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
1864 }
1865
1866 static int test_ssl_bio_change_rbio(void)
1867 {
1868     return execute_test_ssl_bio(0, CHANGE_RBIO);
1869 }
1870
1871 static int test_ssl_bio_change_wbio(void)
1872 {
1873     return execute_test_ssl_bio(0, CHANGE_WBIO);
1874 }
1875
1876 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
1877 typedef struct {
1878     /* The list of sig algs */
1879     const int *list;
1880     /* The length of the list */
1881     size_t listlen;
1882     /* A sigalgs list in string format */
1883     const char *liststr;
1884     /* Whether setting the list should succeed */
1885     int valid;
1886     /* Whether creating a connection with the list should succeed */
1887     int connsuccess;
1888 } sigalgs_list;
1889
1890 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
1891 # ifndef OPENSSL_NO_EC
1892 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
1893 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
1894 # endif
1895 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
1896 static const int invalidlist2[] = {NID_sha256, NID_undef};
1897 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
1898 static const int invalidlist4[] = {NID_sha256};
1899 static const sigalgs_list testsigalgs[] = {
1900     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
1901 # ifndef OPENSSL_NO_EC
1902     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
1903     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
1904 # endif
1905     {NULL, 0, "RSA+SHA256", 1, 1},
1906 # ifndef OPENSSL_NO_EC
1907     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
1908     {NULL, 0, "ECDSA+SHA512", 1, 0},
1909 # endif
1910     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
1911     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
1912     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
1913     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
1914     {NULL, 0, "RSA", 0, 0},
1915     {NULL, 0, "SHA256", 0, 0},
1916     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
1917     {NULL, 0, "Invalid", 0, 0}
1918 };
1919
1920 static int test_set_sigalgs(int idx)
1921 {
1922     SSL_CTX *cctx = NULL, *sctx = NULL;
1923     SSL *clientssl = NULL, *serverssl = NULL;
1924     int testresult = 0;
1925     const sigalgs_list *curr;
1926     int testctx;
1927
1928     /* Should never happen */
1929     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
1930         return 0;
1931
1932     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
1933     curr = testctx ? &testsigalgs[idx]
1934                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
1935
1936     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1937                                        TLS1_VERSION, TLS_MAX_VERSION,
1938                                        &sctx, &cctx, cert, privkey)))
1939         return 0;
1940
1941     /*
1942      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
1943      * for TLSv1.2 for now until we add a new API.
1944      */
1945     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1946
1947     if (testctx) {
1948         int ret;
1949
1950         if (curr->list != NULL)
1951             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
1952         else
1953             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
1954
1955         if (!ret) {
1956             if (curr->valid)
1957                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
1958             else
1959                 testresult = 1;
1960             goto end;
1961         }
1962         if (!curr->valid) {
1963             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
1964             goto end;
1965         }
1966     }
1967
1968     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1969                                       &clientssl, NULL, NULL)))
1970         goto end;
1971
1972     if (!testctx) {
1973         int ret;
1974
1975         if (curr->list != NULL)
1976             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
1977         else
1978             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
1979         if (!ret) {
1980             if (curr->valid)
1981                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
1982             else
1983                 testresult = 1;
1984             goto end;
1985         }
1986         if (!curr->valid)
1987             goto end;
1988     }
1989
1990     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
1991                                            SSL_ERROR_NONE),
1992                 curr->connsuccess))
1993         goto end;
1994
1995     testresult = 1;
1996
1997  end:
1998     SSL_free(serverssl);
1999     SSL_free(clientssl);
2000     SSL_CTX_free(sctx);
2001     SSL_CTX_free(cctx);
2002
2003     return testresult;
2004 }
2005 #endif
2006
2007 #ifndef OPENSSL_NO_TLS1_3
2008 static int psk_client_cb_cnt = 0;
2009 static int psk_server_cb_cnt = 0;
2010
2011 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
2012                           size_t *idlen, SSL_SESSION **sess)
2013 {
2014     switch (++use_session_cb_cnt) {
2015     case 1:
2016         /* The first call should always have a NULL md */
2017         if (md != NULL)
2018             return 0;
2019         break;
2020
2021     case 2:
2022         /* The second call should always have an md */
2023         if (md == NULL)
2024             return 0;
2025         break;
2026
2027     default:
2028         /* We should only be called a maximum of twice */
2029         return 0;
2030     }
2031
2032     if (clientpsk != NULL)
2033         SSL_SESSION_up_ref(clientpsk);
2034
2035     *sess = clientpsk;
2036     *id = (const unsigned char *)pskid;
2037     *idlen = strlen(pskid);
2038
2039     return 1;
2040 }
2041
2042 #ifndef OPENSSL_NO_PSK
2043 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
2044                                   unsigned int max_id_len,
2045                                   unsigned char *psk,
2046                                   unsigned int max_psk_len)
2047 {
2048     unsigned int psklen = 0;
2049
2050     psk_client_cb_cnt++;
2051
2052     if (strlen(pskid) + 1 > max_id_len)
2053         return 0;
2054
2055     /* We should only ever be called a maximum of twice per connection */
2056     if (psk_client_cb_cnt > 2)
2057         return 0;
2058
2059     if (clientpsk == NULL)
2060         return 0;
2061
2062     /* We'll reuse the PSK we set up for TLSv1.3 */
2063     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
2064         return 0;
2065     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
2066     strncpy(id, pskid, max_id_len);
2067
2068     return psklen;
2069 }
2070 #endif /* OPENSSL_NO_PSK */
2071
2072 static int find_session_cb(SSL *ssl, const unsigned char *identity,
2073                            size_t identity_len, SSL_SESSION **sess)
2074 {
2075     find_session_cb_cnt++;
2076
2077     /* We should only ever be called a maximum of twice per connection */
2078     if (find_session_cb_cnt > 2)
2079         return 0;
2080
2081     if (serverpsk == NULL)
2082         return 0;
2083
2084     /* Identity should match that set by the client */
2085     if (strlen(srvid) != identity_len
2086             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
2087         /* No PSK found, continue but without a PSK */
2088         *sess = NULL;
2089         return 1;
2090     }
2091
2092     SSL_SESSION_up_ref(serverpsk);
2093     *sess = serverpsk;
2094
2095     return 1;
2096 }
2097
2098 #ifndef OPENSSL_NO_PSK
2099 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
2100                                   unsigned char *psk, unsigned int max_psk_len)
2101 {
2102     unsigned int psklen = 0;
2103
2104     psk_server_cb_cnt++;
2105
2106     /* We should only ever be called a maximum of twice per connection */
2107     if (find_session_cb_cnt > 2)
2108         return 0;
2109
2110     if (serverpsk == NULL)
2111         return 0;
2112
2113     /* Identity should match that set by the client */
2114     if (strcmp(srvid, identity) != 0) {
2115         return 0;
2116     }
2117
2118     /* We'll reuse the PSK we set up for TLSv1.3 */
2119     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
2120         return 0;
2121     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
2122
2123     return psklen;
2124 }
2125 #endif /* OPENSSL_NO_PSK */
2126
2127 #define MSG1    "Hello"
2128 #define MSG2    "World."
2129 #define MSG3    "This"
2130 #define MSG4    "is"
2131 #define MSG5    "a"
2132 #define MSG6    "test"
2133 #define MSG7    "message."
2134
2135 #define TLS13_AES_128_GCM_SHA256_BYTES  ((const unsigned char *)"\x13\x01")
2136 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
2137 #define TLS13_CHACHA20_POLY1305_SHA256_BYTES ((const unsigned char *)"\x13\x03")
2138 #define TLS13_AES_128_CCM_SHA256_BYTES ((const unsigned char *)"\x13\x04")
2139 #define TLS13_AES_128_CCM_8_SHA256_BYTES ((const unsigned char *)"\x13\05")
2140
2141
2142 static SSL_SESSION *create_a_psk(SSL *ssl)
2143 {
2144     const SSL_CIPHER *cipher = NULL;
2145     const unsigned char key[] = {
2146         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
2147         0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
2148         0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
2149         0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
2150         0x2c, 0x2d, 0x2e, 0x2f
2151     };
2152     SSL_SESSION *sess = NULL;
2153
2154     cipher = SSL_CIPHER_find(ssl, TLS13_AES_256_GCM_SHA384_BYTES);
2155     sess = SSL_SESSION_new();
2156     if (!TEST_ptr(sess)
2157             || !TEST_ptr(cipher)
2158             || !TEST_true(SSL_SESSION_set1_master_key(sess, key,
2159                                                       sizeof(key)))
2160             || !TEST_true(SSL_SESSION_set_cipher(sess, cipher))
2161             || !TEST_true(
2162                     SSL_SESSION_set_protocol_version(sess,
2163                                                      TLS1_3_VERSION))) {
2164         SSL_SESSION_free(sess);
2165         return NULL;
2166     }
2167     return sess;
2168 }
2169
2170 /*
2171  * Helper method to setup objects for early data test. Caller frees objects on
2172  * error.
2173  */
2174 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
2175                                 SSL **serverssl, SSL_SESSION **sess, int idx)
2176 {
2177     if (*sctx == NULL
2178             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2179                                               TLS_client_method(),
2180                                               TLS1_VERSION, TLS_MAX_VERSION,
2181                                               sctx, cctx, cert, privkey)))
2182         return 0;
2183
2184     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
2185         return 0;
2186
2187     if (idx == 1) {
2188         /* When idx == 1 we repeat the tests with read_ahead set */
2189         SSL_CTX_set_read_ahead(*cctx, 1);
2190         SSL_CTX_set_read_ahead(*sctx, 1);
2191     } else if (idx == 2) {
2192         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
2193         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
2194         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
2195         use_session_cb_cnt = 0;
2196         find_session_cb_cnt = 0;
2197         srvid = pskid;
2198     }
2199
2200     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
2201                                       NULL, NULL)))
2202         return 0;
2203
2204     /*
2205      * For one of the run throughs (doesn't matter which one), we'll try sending
2206      * some SNI data in the initial ClientHello. This will be ignored (because
2207      * there is no SNI cb set up by the server), so it should not impact
2208      * early_data.
2209      */
2210     if (idx == 1
2211             && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
2212         return 0;
2213
2214     if (idx == 2) {
2215         clientpsk = create_a_psk(*clientssl);
2216         if (!TEST_ptr(clientpsk)
2217                    /*
2218                     * We just choose an arbitrary value for max_early_data which
2219                     * should be big enough for testing purposes.
2220                     */
2221                 || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
2222                                                              0x100))
2223                 || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
2224             SSL_SESSION_free(clientpsk);
2225             clientpsk = NULL;
2226             return 0;
2227         }
2228         serverpsk = clientpsk;
2229
2230         if (sess != NULL) {
2231             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
2232                 SSL_SESSION_free(clientpsk);
2233                 SSL_SESSION_free(serverpsk);
2234                 clientpsk = serverpsk = NULL;
2235                 return 0;
2236             }
2237             *sess = clientpsk;
2238         }
2239         return 1;
2240     }
2241
2242     if (sess == NULL)
2243         return 1;
2244
2245     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
2246                                          SSL_ERROR_NONE)))
2247         return 0;
2248
2249     *sess = SSL_get1_session(*clientssl);
2250     SSL_shutdown(*clientssl);
2251     SSL_shutdown(*serverssl);
2252     SSL_free(*serverssl);
2253     SSL_free(*clientssl);
2254     *serverssl = *clientssl = NULL;
2255
2256     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
2257                                       clientssl, NULL, NULL))
2258             || !TEST_true(SSL_set_session(*clientssl, *sess)))
2259         return 0;
2260
2261     return 1;
2262 }
2263
2264 static int test_early_data_read_write(int idx)
2265 {
2266     SSL_CTX *cctx = NULL, *sctx = NULL;
2267     SSL *clientssl = NULL, *serverssl = NULL;
2268     int testresult = 0;
2269     SSL_SESSION *sess = NULL;
2270     unsigned char buf[20], data[1024];
2271     size_t readbytes, written, eoedlen, rawread, rawwritten;
2272     BIO *rbio;
2273
2274     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2275                                         &serverssl, &sess, idx)))
2276         goto end;
2277
2278     /* Write and read some early data */
2279     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2280                                         &written))
2281             || !TEST_size_t_eq(written, strlen(MSG1))
2282             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
2283                                                 sizeof(buf), &readbytes),
2284                             SSL_READ_EARLY_DATA_SUCCESS)
2285             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
2286             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2287                             SSL_EARLY_DATA_ACCEPTED))
2288         goto end;
2289
2290     /*
2291      * Server should be able to write data, and client should be able to
2292      * read it.
2293      */
2294     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
2295                                         &written))
2296             || !TEST_size_t_eq(written, strlen(MSG2))
2297             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2298             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2299         goto end;
2300
2301     /* Even after reading normal data, client should be able write early data */
2302     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
2303                                         &written))
2304             || !TEST_size_t_eq(written, strlen(MSG3)))
2305         goto end;
2306
2307     /* Server should still be able read early data after writing data */
2308     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2309                                          &readbytes),
2310                      SSL_READ_EARLY_DATA_SUCCESS)
2311             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
2312         goto end;
2313
2314     /* Write more data from server and read it from client */
2315     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
2316                                         &written))
2317             || !TEST_size_t_eq(written, strlen(MSG4))
2318             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2319             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
2320         goto end;
2321
2322     /*
2323      * If client writes normal data it should mean writing early data is no
2324      * longer possible.
2325      */
2326     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
2327             || !TEST_size_t_eq(written, strlen(MSG5))
2328             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2329                             SSL_EARLY_DATA_ACCEPTED))
2330         goto end;
2331
2332     /*
2333      * At this point the client has written EndOfEarlyData, ClientFinished and
2334      * normal (fully protected) data. We are going to cause a delay between the
2335      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
2336      * in the read BIO, and then just put back the EndOfEarlyData message.
2337      */
2338     rbio = SSL_get_rbio(serverssl);
2339     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
2340             || !TEST_size_t_lt(rawread, sizeof(data))
2341             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
2342         goto end;
2343
2344     /* Record length is in the 4th and 5th bytes of the record header */
2345     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
2346     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
2347             || !TEST_size_t_eq(rawwritten, eoedlen))
2348         goto end;
2349
2350     /* Server should be told that there is no more early data */
2351     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2352                                          &readbytes),
2353                      SSL_READ_EARLY_DATA_FINISH)
2354             || !TEST_size_t_eq(readbytes, 0))
2355         goto end;
2356
2357     /*
2358      * Server has not finished init yet, so should still be able to write early
2359      * data.
2360      */
2361     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
2362                                         &written))
2363             || !TEST_size_t_eq(written, strlen(MSG6)))
2364         goto end;
2365
2366     /* Push the ClientFinished and the normal data back into the server rbio */
2367     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
2368                                 &rawwritten))
2369             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
2370         goto end;
2371
2372     /* Server should be able to read normal data */
2373     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2374             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
2375         goto end;
2376
2377     /* Client and server should not be able to write/read early data now */
2378     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
2379                                          &written)))
2380         goto end;
2381     ERR_clear_error();
2382     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2383                                          &readbytes),
2384                      SSL_READ_EARLY_DATA_ERROR))
2385         goto end;
2386     ERR_clear_error();
2387
2388     /* Client should be able to read the data sent by the server */
2389     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2390             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
2391         goto end;
2392
2393     /*
2394      * Make sure we process the two NewSessionTickets. These arrive
2395      * post-handshake. We attempt reads which we do not expect to return any
2396      * data.
2397      */
2398     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2399             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
2400                            &readbytes)))
2401         goto end;
2402
2403     /* Server should be able to write normal data */
2404     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
2405             || !TEST_size_t_eq(written, strlen(MSG7))
2406             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2407             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
2408         goto end;
2409
2410     SSL_SESSION_free(sess);
2411     sess = SSL_get1_session(clientssl);
2412     use_session_cb_cnt = 0;
2413     find_session_cb_cnt = 0;
2414
2415     SSL_shutdown(clientssl);
2416     SSL_shutdown(serverssl);
2417     SSL_free(serverssl);
2418     SSL_free(clientssl);
2419     serverssl = clientssl = NULL;
2420     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2421                                       &clientssl, NULL, NULL))
2422             || !TEST_true(SSL_set_session(clientssl, sess)))
2423         goto end;
2424
2425     /* Write and read some early data */
2426     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2427                                         &written))
2428             || !TEST_size_t_eq(written, strlen(MSG1))
2429             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2430                                                 &readbytes),
2431                             SSL_READ_EARLY_DATA_SUCCESS)
2432             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
2433         goto end;
2434
2435     if (!TEST_int_gt(SSL_connect(clientssl), 0)
2436             || !TEST_int_gt(SSL_accept(serverssl), 0))
2437         goto end;
2438
2439     /* Client and server should not be able to write/read early data now */
2440     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
2441                                          &written)))
2442         goto end;
2443     ERR_clear_error();
2444     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2445                                          &readbytes),
2446                      SSL_READ_EARLY_DATA_ERROR))
2447         goto end;
2448     ERR_clear_error();
2449
2450     /* Client and server should be able to write/read normal data */
2451     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
2452             || !TEST_size_t_eq(written, strlen(MSG5))
2453             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2454             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
2455         goto end;
2456
2457     testresult = 1;
2458
2459  end:
2460     SSL_SESSION_free(sess);
2461     SSL_SESSION_free(clientpsk);
2462     SSL_SESSION_free(serverpsk);
2463     clientpsk = serverpsk = NULL;
2464     SSL_free(serverssl);
2465     SSL_free(clientssl);
2466     SSL_CTX_free(sctx);
2467     SSL_CTX_free(cctx);
2468     return testresult;
2469 }
2470
2471 static int allow_ed_cb_called = 0;
2472
2473 static int allow_early_data_cb(SSL *s, void *arg)
2474 {
2475     int *usecb = (int *)arg;
2476
2477     allow_ed_cb_called++;
2478
2479     if (*usecb == 1)
2480         return 0;
2481
2482     return 1;
2483 }
2484
2485 /*
2486  * idx == 0: Standard early_data setup
2487  * idx == 1: early_data setup using read_ahead
2488  * usecb == 0: Don't use a custom early data callback
2489  * usecb == 1: Use a custom early data callback and reject the early data
2490  * usecb == 2: Use a custom early data callback and accept the early data
2491  * confopt == 0: Configure anti-replay directly
2492  * confopt == 1: Configure anti-replay using SSL_CONF
2493  */
2494 static int test_early_data_replay_int(int idx, int usecb, int confopt)
2495 {
2496     SSL_CTX *cctx = NULL, *sctx = NULL;
2497     SSL *clientssl = NULL, *serverssl = NULL;
2498     int testresult = 0;
2499     SSL_SESSION *sess = NULL;
2500     size_t readbytes, written;
2501     unsigned char buf[20];
2502
2503     allow_ed_cb_called = 0;
2504
2505     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2506                                        TLS1_VERSION, TLS_MAX_VERSION, &sctx,
2507                                        &cctx, cert, privkey)))
2508         return 0;
2509
2510     if (usecb > 0) {
2511         if (confopt == 0) {
2512             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
2513         } else {
2514             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
2515
2516             if (!TEST_ptr(confctx))
2517                 goto end;
2518             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
2519                                             | SSL_CONF_FLAG_SERVER);
2520             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
2521             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
2522                              2)) {
2523                 SSL_CONF_CTX_free(confctx);
2524                 goto end;
2525             }
2526             SSL_CONF_CTX_free(confctx);
2527         }
2528         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
2529     }
2530
2531     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2532                                         &serverssl, &sess, idx)))
2533         goto end;
2534
2535     /*
2536      * The server is configured to accept early data. Create a connection to
2537      * "use up" the ticket
2538      */
2539     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2540             || !TEST_true(SSL_session_reused(clientssl)))
2541         goto end;
2542
2543     SSL_shutdown(clientssl);
2544     SSL_shutdown(serverssl);
2545     SSL_free(serverssl);
2546     SSL_free(clientssl);
2547     serverssl = clientssl = NULL;
2548
2549     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2550                                       &clientssl, NULL, NULL))
2551             || !TEST_true(SSL_set_session(clientssl, sess)))
2552         goto end;
2553
2554     /* Write and read some early data */
2555     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2556                                         &written))
2557             || !TEST_size_t_eq(written, strlen(MSG1)))
2558         goto end;
2559
2560     if (usecb <= 1) {
2561         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2562                                              &readbytes),
2563                          SSL_READ_EARLY_DATA_FINISH)
2564                    /*
2565                     * The ticket was reused, so the we should have rejected the
2566                     * early data
2567                     */
2568                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2569                                 SSL_EARLY_DATA_REJECTED))
2570             goto end;
2571     } else {
2572         /* In this case the callback decides to accept the early data */
2573         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2574                                              &readbytes),
2575                          SSL_READ_EARLY_DATA_SUCCESS)
2576                 || !TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
2577                    /*
2578                     * Server will have sent its flight so client can now send
2579                     * end of early data and complete its half of the handshake
2580                     */
2581                 || !TEST_int_gt(SSL_connect(clientssl), 0)
2582                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2583                                              &readbytes),
2584                                 SSL_READ_EARLY_DATA_FINISH)
2585                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2586                                 SSL_EARLY_DATA_ACCEPTED))
2587             goto end;
2588     }
2589
2590     /* Complete the connection */
2591     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2592             || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
2593             || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
2594         goto end;
2595
2596     testresult = 1;
2597
2598  end:
2599     SSL_SESSION_free(sess);
2600     SSL_SESSION_free(clientpsk);
2601     SSL_SESSION_free(serverpsk);
2602     clientpsk = serverpsk = NULL;
2603     SSL_free(serverssl);
2604     SSL_free(clientssl);
2605     SSL_CTX_free(sctx);
2606     SSL_CTX_free(cctx);
2607     return testresult;
2608 }
2609
2610 static int test_early_data_replay(int idx)
2611 {
2612     int ret = 1, usecb, confopt;
2613
2614     for (usecb = 0; usecb < 3; usecb++) {
2615         for (confopt = 0; confopt < 2; confopt++)
2616             ret &= test_early_data_replay_int(idx, usecb, confopt);
2617     }
2618
2619     return ret;
2620 }
2621
2622 /*
2623  * Helper function to test that a server attempting to read early data can
2624  * handle a connection from a client where the early data should be skipped.
2625  * testtype: 0 == No HRR
2626  * testtype: 1 == HRR
2627  * testtype: 2 == HRR, invalid early_data sent after HRR
2628  * testtype: 3 == recv_max_early_data set to 0
2629  */
2630 static int early_data_skip_helper(int testtype, int idx)
2631 {
2632     SSL_CTX *cctx = NULL, *sctx = NULL;
2633     SSL *clientssl = NULL, *serverssl = NULL;
2634     int testresult = 0;
2635     SSL_SESSION *sess = NULL;
2636     unsigned char buf[20];
2637     size_t readbytes, written;
2638
2639     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2640                                         &serverssl, &sess, idx)))
2641         goto end;
2642
2643     if (testtype == 1 || testtype == 2) {
2644         /* Force an HRR to occur */
2645         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2646             goto end;
2647     } else if (idx == 2) {
2648         /*
2649          * We force early_data rejection by ensuring the PSK identity is
2650          * unrecognised
2651          */
2652         srvid = "Dummy Identity";
2653     } else {
2654         /*
2655          * Deliberately corrupt the creation time. We take 20 seconds off the
2656          * time. It could be any value as long as it is not within tolerance.
2657          * This should mean the ticket is rejected.
2658          */
2659         if (!TEST_true(SSL_SESSION_set_time(sess, (long)(time(NULL) - 20))))
2660             goto end;
2661     }
2662
2663     if (testtype == 3
2664             && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
2665         goto end;
2666
2667     /* Write some early data */
2668     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2669                                         &written))
2670             || !TEST_size_t_eq(written, strlen(MSG1)))
2671         goto end;
2672
2673     /* Server should reject the early data */
2674     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2675                                          &readbytes),
2676                      SSL_READ_EARLY_DATA_FINISH)
2677             || !TEST_size_t_eq(readbytes, 0)
2678             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2679                             SSL_EARLY_DATA_REJECTED))
2680         goto end;
2681
2682     switch (testtype) {
2683     case 0:
2684         /* Nothing to do */
2685         break;
2686
2687     case 1:
2688         /*
2689          * Finish off the handshake. We perform the same writes and reads as
2690          * further down but we expect them to fail due to the incomplete
2691          * handshake.
2692          */
2693         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2694                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
2695                                &readbytes)))
2696             goto end;
2697         break;
2698
2699     case 2:
2700         {
2701             BIO *wbio = SSL_get_wbio(clientssl);
2702             /* A record that will appear as bad early_data */
2703             const unsigned char bad_early_data[] = {
2704                 0x17, 0x03, 0x03, 0x00, 0x01, 0x00
2705             };
2706
2707             /*
2708              * We force the client to attempt a write. This will fail because
2709              * we're still in the handshake. It will cause the second
2710              * ClientHello to be sent.
2711              */
2712             if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2),
2713                                          &written)))
2714                 goto end;
2715
2716             /*
2717              * Inject some early_data after the second ClientHello. This should
2718              * cause the server to fail
2719              */
2720             if (!TEST_true(BIO_write_ex(wbio, bad_early_data,
2721                                         sizeof(bad_early_data), &written)))
2722                 goto end;
2723         }
2724         /* fallthrough */
2725
2726     case 3:
2727         /*
2728          * This client has sent more early_data than we are willing to skip
2729          * (case 3) or sent invalid early_data (case 2) so the connection should
2730          * abort.
2731          */
2732         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2733                 || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
2734             goto end;
2735
2736         /* Connection has failed - nothing more to do */
2737         testresult = 1;
2738         goto end;
2739
2740     default:
2741         TEST_error("Invalid test type");
2742         goto end;
2743     }
2744
2745     /*
2746      * Should be able to send normal data despite rejection of early data. The
2747      * early_data should be skipped.
2748      */
2749     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2750             || !TEST_size_t_eq(written, strlen(MSG2))
2751             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2752                             SSL_EARLY_DATA_REJECTED)
2753             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2754             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2755         goto end;
2756
2757     testresult = 1;
2758
2759  end:
2760     SSL_SESSION_free(clientpsk);
2761     SSL_SESSION_free(serverpsk);
2762     clientpsk = serverpsk = NULL;
2763     SSL_SESSION_free(sess);
2764     SSL_free(serverssl);
2765     SSL_free(clientssl);
2766     SSL_CTX_free(sctx);
2767     SSL_CTX_free(cctx);
2768     return testresult;
2769 }
2770
2771 /*
2772  * Test that a server attempting to read early data can handle a connection
2773  * from a client where the early data is not acceptable.
2774  */
2775 static int test_early_data_skip(int idx)
2776 {
2777     return early_data_skip_helper(0, idx);
2778 }
2779
2780 /*
2781  * Test that a server attempting to read early data can handle a connection
2782  * from a client where an HRR occurs.
2783  */
2784 static int test_early_data_skip_hrr(int idx)
2785 {
2786     return early_data_skip_helper(1, idx);
2787 }
2788
2789 /*
2790  * Test that a server attempting to read early data can handle a connection
2791  * from a client where an HRR occurs and correctly fails if early_data is sent
2792  * after the HRR
2793  */
2794 static int test_early_data_skip_hrr_fail(int idx)
2795 {
2796     return early_data_skip_helper(2, idx);
2797 }
2798
2799 /*
2800  * Test that a server attempting to read early data will abort if it tries to
2801  * skip over too much.
2802  */
2803 static int test_early_data_skip_abort(int idx)
2804 {
2805     return early_data_skip_helper(3, idx);
2806 }
2807
2808 /*
2809  * Test that a server attempting to read early data can handle a connection
2810  * from a client that doesn't send any.
2811  */
2812 static int test_early_data_not_sent(int idx)
2813 {
2814     SSL_CTX *cctx = NULL, *sctx = NULL;
2815     SSL *clientssl = NULL, *serverssl = NULL;
2816     int testresult = 0;
2817     SSL_SESSION *sess = NULL;
2818     unsigned char buf[20];
2819     size_t readbytes, written;
2820
2821     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2822                                         &serverssl, &sess, idx)))
2823         goto end;
2824
2825     /* Write some data - should block due to handshake with server */
2826     SSL_set_connect_state(clientssl);
2827     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
2828         goto end;
2829
2830     /* Server should detect that early data has not been sent */
2831     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2832                                          &readbytes),
2833                      SSL_READ_EARLY_DATA_FINISH)
2834             || !TEST_size_t_eq(readbytes, 0)
2835             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2836                             SSL_EARLY_DATA_NOT_SENT)
2837             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2838                             SSL_EARLY_DATA_NOT_SENT))
2839         goto end;
2840
2841     /* Continue writing the message we started earlier */
2842     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2843             || !TEST_size_t_eq(written, strlen(MSG1))
2844             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2845             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
2846             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
2847             || !TEST_size_t_eq(written, strlen(MSG2)))
2848         goto end;
2849
2850     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2851             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2852         goto end;
2853
2854     testresult = 1;
2855
2856  end:
2857     SSL_SESSION_free(sess);
2858     SSL_SESSION_free(clientpsk);
2859     SSL_SESSION_free(serverpsk);
2860     clientpsk = serverpsk = NULL;
2861     SSL_free(serverssl);
2862     SSL_free(clientssl);
2863     SSL_CTX_free(sctx);
2864     SSL_CTX_free(cctx);
2865     return testresult;
2866 }
2867
2868 static const char *servalpn;
2869
2870 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
2871                           unsigned char *outlen, const unsigned char *in,
2872                           unsigned int inlen, void *arg)
2873 {
2874     unsigned int protlen = 0;
2875     const unsigned char *prot;
2876
2877     for (prot = in; prot < in + inlen; prot += protlen) {
2878         protlen = *prot++;
2879         if (in + inlen < prot + protlen)
2880             return SSL_TLSEXT_ERR_NOACK;
2881
2882         if (protlen == strlen(servalpn)
2883                 && memcmp(prot, servalpn, protlen) == 0) {
2884             *out = prot;
2885             *outlen = protlen;
2886             return SSL_TLSEXT_ERR_OK;
2887         }
2888     }
2889
2890     return SSL_TLSEXT_ERR_NOACK;
2891 }
2892
2893 /* Test that a PSK can be used to send early_data */
2894 static int test_early_data_psk(int idx)
2895 {
2896     SSL_CTX *cctx = NULL, *sctx = NULL;
2897     SSL *clientssl = NULL, *serverssl = NULL;
2898     int testresult = 0;
2899     SSL_SESSION *sess = NULL;
2900     unsigned char alpnlist[] = {
2901         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
2902         'l', 'p', 'n'
2903     };
2904 #define GOODALPNLEN     9
2905 #define BADALPNLEN      8
2906 #define GOODALPN        (alpnlist)
2907 #define BADALPN         (alpnlist + GOODALPNLEN)
2908     int err = 0;
2909     unsigned char buf[20];
2910     size_t readbytes, written;
2911     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
2912     int edstatus = SSL_EARLY_DATA_ACCEPTED;
2913
2914     /* We always set this up with a final parameter of "2" for PSK */
2915     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2916                                         &serverssl, &sess, 2)))
2917         goto end;
2918
2919     servalpn = "goodalpn";
2920
2921     /*
2922      * Note: There is no test for inconsistent SNI with late client detection.
2923      * This is because servers do not acknowledge SNI even if they are using
2924      * it in a resumption handshake - so it is not actually possible for a
2925      * client to detect a problem.
2926      */
2927     switch (idx) {
2928     case 0:
2929         /* Set inconsistent SNI (early client detection) */
2930         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
2931         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2932                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
2933             goto end;
2934         break;
2935
2936     case 1:
2937         /* Set inconsistent ALPN (early client detection) */
2938         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
2939         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
2940         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
2941                                                       GOODALPNLEN))
2942                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
2943                                                    BADALPNLEN)))
2944             goto end;
2945         break;
2946
2947     case 2:
2948         /*
2949          * Set invalid protocol version. Technically this affects PSKs without
2950          * early_data too, but we test it here because it is similar to the
2951          * SNI/ALPN consistency tests.
2952          */
2953         err = SSL_R_BAD_PSK;
2954         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
2955             goto end;
2956         break;
2957
2958     case 3:
2959         /*
2960          * Set inconsistent SNI (server side). In this case the connection
2961          * will succeed and accept early_data. In TLSv1.3 on the server side SNI
2962          * is associated with each handshake - not the session. Therefore it
2963          * should not matter that we used a different server name last time.
2964          */
2965         SSL_SESSION_free(serverpsk);
2966         serverpsk = SSL_SESSION_dup(clientpsk);
2967         if (!TEST_ptr(serverpsk)
2968                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
2969             goto end;
2970         /* Fall through */
2971     case 4:
2972         /* Set consistent SNI */
2973         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2974                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
2975                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
2976                                 hostname_cb)))
2977             goto end;
2978         break;
2979
2980     case 5:
2981         /*
2982          * Set inconsistent ALPN (server detected). In this case the connection
2983          * will succeed but reject early_data.
2984          */
2985         servalpn = "badalpn";
2986         edstatus = SSL_EARLY_DATA_REJECTED;
2987         readearlyres = SSL_READ_EARLY_DATA_FINISH;
2988         /* Fall through */
2989     case 6:
2990         /*
2991          * Set consistent ALPN.
2992          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
2993          * accepts a list of protos (each one length prefixed).
2994          * SSL_set1_alpn_selected accepts a single protocol (not length
2995          * prefixed)
2996          */
2997         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
2998                                                       GOODALPNLEN - 1))
2999                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
3000                                                    GOODALPNLEN)))
3001             goto end;
3002
3003         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
3004         break;
3005
3006     case 7:
3007         /* Set inconsistent ALPN (late client detection) */
3008         SSL_SESSION_free(serverpsk);
3009         serverpsk = SSL_SESSION_dup(clientpsk);
3010         if (!TEST_ptr(serverpsk)
3011                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
3012                                                              BADALPN + 1,
3013                                                              BADALPNLEN - 1))
3014                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
3015                                                              GOODALPN + 1,
3016                                                              GOODALPNLEN - 1))
3017                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
3018                                                    sizeof(alpnlist))))
3019             goto end;
3020         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
3021         edstatus = SSL_EARLY_DATA_ACCEPTED;
3022         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
3023         /* SSL_connect() call should fail */
3024         connectres = -1;
3025         break;
3026
3027     default:
3028         TEST_error("Bad test index");
3029         goto end;
3030     }
3031
3032     SSL_set_connect_state(clientssl);
3033     if (err != 0) {
3034         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3035                                             &written))
3036                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
3037                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
3038             goto end;
3039     } else {
3040         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3041                                             &written)))
3042             goto end;
3043
3044         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3045                                              &readbytes), readearlyres)
3046                 || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
3047                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3048                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
3049                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
3050             goto end;
3051     }
3052
3053     testresult = 1;
3054
3055  end:
3056     SSL_SESSION_free(sess);
3057     SSL_SESSION_free(clientpsk);
3058     SSL_SESSION_free(serverpsk);
3059     clientpsk = serverpsk = NULL;
3060     SSL_free(serverssl);
3061     SSL_free(clientssl);
3062     SSL_CTX_free(sctx);
3063     SSL_CTX_free(cctx);
3064     return testresult;
3065 }
3066
3067 /*
3068  * Test TLSv1.3 PSK can be used to send early_data with all 5 ciphersuites
3069  * idx == 0: Test with TLS1_3_RFC_AES_128_GCM_SHA256
3070  * idx == 1: Test with TLS1_3_RFC_AES_256_GCM_SHA384
3071  * idx == 2: Test with TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
3072  * idx == 3: Test with TLS1_3_RFC_AES_128_CCM_SHA256
3073  * idx == 4: Test with TLS1_3_RFC_AES_128_CCM_8_SHA256
3074  */
3075 static int test_early_data_psk_with_all_ciphers(int idx)
3076 {
3077     SSL_CTX *cctx = NULL, *sctx = NULL;
3078     SSL *clientssl = NULL, *serverssl = NULL;
3079     int testresult = 0;
3080     SSL_SESSION *sess = NULL;
3081     unsigned char buf[20];
3082     size_t readbytes, written;
3083     const SSL_CIPHER *cipher;
3084     const char *cipher_str[] = {
3085         TLS1_3_RFC_AES_128_GCM_SHA256,
3086         TLS1_3_RFC_AES_256_GCM_SHA384,
3087 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3088         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
3089 # else
3090         NULL,
3091 # endif
3092         TLS1_3_RFC_AES_128_CCM_SHA256,
3093         TLS1_3_RFC_AES_128_CCM_8_SHA256
3094     };
3095     const unsigned char *cipher_bytes[] = {
3096         TLS13_AES_128_GCM_SHA256_BYTES,
3097         TLS13_AES_256_GCM_SHA384_BYTES,
3098 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3099         TLS13_CHACHA20_POLY1305_SHA256_BYTES,
3100 # else
3101         NULL,
3102 # endif
3103         TLS13_AES_128_CCM_SHA256_BYTES,
3104         TLS13_AES_128_CCM_8_SHA256_BYTES
3105     };
3106
3107     if (cipher_str[idx] == NULL)
3108         return 1;
3109
3110     /* We always set this up with a final parameter of "2" for PSK */
3111     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3112                                         &serverssl, &sess, 2)))
3113         goto end;
3114
3115     if (!TEST_true(SSL_set_ciphersuites(clientssl, cipher_str[idx]))
3116             || !TEST_true(SSL_set_ciphersuites(serverssl, cipher_str[idx])))
3117         goto end;
3118
3119     /*
3120      * 'setupearly_data_test' creates only one instance of SSL_SESSION
3121      * and assigns to both client and server with incremented reference
3122      * and the same instance is updated in 'sess'.
3123      * So updating ciphersuite in 'sess' which will get reflected in
3124      * PSK handshake using psk use sess and find sess cb.
3125      */
3126     cipher = SSL_CIPHER_find(clientssl, cipher_bytes[idx]);
3127     if (!TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher)))
3128         goto end;
3129
3130     SSL_set_connect_state(clientssl);
3131     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3132                                         &written)))
3133         goto end;
3134
3135     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3136                                          &readbytes),
3137                                          SSL_READ_EARLY_DATA_SUCCESS)
3138             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
3139             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3140                                                       SSL_EARLY_DATA_ACCEPTED)
3141             || !TEST_int_eq(SSL_connect(clientssl), 1)
3142             || !TEST_int_eq(SSL_accept(serverssl), 1))
3143         goto end;
3144
3145     /* Send some normal data from client to server */
3146     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
3147             || !TEST_size_t_eq(written, strlen(MSG2)))
3148         goto end;
3149
3150     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3151             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3152         goto end;
3153
3154     testresult = 1;
3155  end:
3156     SSL_SESSION_free(sess);
3157     SSL_SESSION_free(clientpsk);
3158     SSL_SESSION_free(serverpsk);
3159     clientpsk = serverpsk = NULL;
3160     if (clientssl != NULL)
3161         SSL_shutdown(clientssl);
3162     if (serverssl != NULL)
3163         SSL_shutdown(serverssl);
3164     SSL_free(serverssl);
3165     SSL_free(clientssl);
3166     SSL_CTX_free(sctx);
3167     SSL_CTX_free(cctx);
3168     return testresult;
3169 }
3170
3171 /*
3172  * Test that a server that doesn't try to read early data can handle a
3173  * client sending some.
3174  */
3175 static int test_early_data_not_expected(int idx)
3176 {
3177     SSL_CTX *cctx = NULL, *sctx = NULL;
3178     SSL *clientssl = NULL, *serverssl = NULL;
3179     int testresult = 0;
3180     SSL_SESSION *sess = NULL;
3181     unsigned char buf[20];
3182     size_t readbytes, written;
3183
3184     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3185                                         &serverssl, &sess, idx)))
3186         goto end;
3187
3188     /* Write some early data */
3189     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3190                                         &written)))
3191         goto end;
3192
3193     /*
3194      * Server should skip over early data and then block waiting for client to
3195      * continue handshake
3196      */
3197     if (!TEST_int_le(SSL_accept(serverssl), 0)
3198      || !TEST_int_gt(SSL_connect(clientssl), 0)
3199      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3200                      SSL_EARLY_DATA_REJECTED)
3201      || !TEST_int_gt(SSL_accept(serverssl), 0)
3202      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3203                      SSL_EARLY_DATA_REJECTED))
3204         goto end;
3205
3206     /* Send some normal data from client to server */
3207     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
3208             || !TEST_size_t_eq(written, strlen(MSG2)))
3209         goto end;
3210
3211     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3212             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3213         goto end;
3214
3215     testresult = 1;
3216
3217  end:
3218     SSL_SESSION_free(sess);
3219     SSL_SESSION_free(clientpsk);
3220     SSL_SESSION_free(serverpsk);
3221     clientpsk = serverpsk = NULL;
3222     SSL_free(serverssl);
3223     SSL_free(clientssl);
3224     SSL_CTX_free(sctx);
3225     SSL_CTX_free(cctx);
3226     return testresult;
3227 }
3228
3229
3230 # ifndef OPENSSL_NO_TLS1_2
3231 /*
3232  * Test that a server attempting to read early data can handle a connection
3233  * from a TLSv1.2 client.
3234  */
3235 static int test_early_data_tls1_2(int idx)
3236 {
3237     SSL_CTX *cctx = NULL, *sctx = NULL;
3238     SSL *clientssl = NULL, *serverssl = NULL;
3239     int testresult = 0;
3240     unsigned char buf[20];
3241     size_t readbytes, written;
3242
3243     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3244                                         &serverssl, NULL, idx)))
3245         goto end;
3246
3247     /* Write some data - should block due to handshake with server */
3248     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
3249     SSL_set_connect_state(clientssl);
3250     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
3251         goto end;
3252
3253     /*
3254      * Server should do TLSv1.2 handshake. First it will block waiting for more
3255      * messages from client after ServerDone. Then SSL_read_early_data should
3256      * finish and detect that early data has not been sent
3257      */
3258     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3259                                          &readbytes),
3260                      SSL_READ_EARLY_DATA_ERROR))
3261         goto end;
3262
3263     /*
3264      * Continue writing the message we started earlier. Will still block waiting
3265      * for the CCS/Finished from server
3266      */
3267     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
3268             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3269                                                 &readbytes),
3270                             SSL_READ_EARLY_DATA_FINISH)
3271             || !TEST_size_t_eq(readbytes, 0)
3272             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3273                             SSL_EARLY_DATA_NOT_SENT))
3274         goto end;
3275
3276     /* Continue writing the message we started earlier */
3277     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
3278             || !TEST_size_t_eq(written, strlen(MSG1))
3279             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3280                             SSL_EARLY_DATA_NOT_SENT)
3281             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3282             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
3283             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
3284             || !TEST_size_t_eq(written, strlen(MSG2))
3285             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
3286             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3287         goto end;
3288
3289     testresult = 1;
3290
3291  end:
3292     SSL_SESSION_free(clientpsk);
3293     SSL_SESSION_free(serverpsk);
3294     clientpsk = serverpsk = NULL;
3295     SSL_free(serverssl);
3296     SSL_free(clientssl);
3297     SSL_CTX_free(sctx);
3298     SSL_CTX_free(cctx);
3299
3300     return testresult;
3301 }
3302 # endif /* OPENSSL_NO_TLS1_2 */
3303
3304 /*
3305  * Test configuring the TLSv1.3 ciphersuites
3306  *
3307  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
3308  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
3309  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
3310  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
3311  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
3312  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
3313  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
3314  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
3315  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
3316  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
3317  */
3318 static int test_set_ciphersuite(int idx)
3319 {
3320     SSL_CTX *cctx = NULL, *sctx = NULL;
3321     SSL *clientssl = NULL, *serverssl = NULL;
3322     int testresult = 0;
3323
3324     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3325                                        TLS1_VERSION, TLS_MAX_VERSION,
3326                                        &sctx, &cctx, cert, privkey))
3327             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
3328                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
3329         goto end;
3330
3331     if (idx >=4 && idx <= 7) {
3332         /* SSL_CTX explicit cipher list */
3333         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
3334             goto end;
3335     }
3336
3337     if (idx == 0 || idx == 4) {
3338         /* Default ciphersuite */
3339         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3340                                                 "TLS_AES_128_GCM_SHA256")))
3341             goto end;
3342     } else if (idx == 1 || idx == 5) {
3343         /* Non default ciphersuite */
3344         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3345                                                 "TLS_AES_128_CCM_SHA256")))
3346             goto end;
3347     }
3348
3349     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3350                                           &clientssl, NULL, NULL)))
3351         goto end;
3352
3353     if (idx == 8 || idx == 9) {
3354         /* SSL explicit cipher list */
3355         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
3356             goto end;
3357     }
3358
3359     if (idx == 2 || idx == 6 || idx == 8) {
3360         /* Default ciphersuite */
3361         if (!TEST_true(SSL_set_ciphersuites(clientssl,
3362                                             "TLS_AES_128_GCM_SHA256")))
3363             goto end;
3364     } else if (idx == 3 || idx == 7 || idx == 9) {
3365         /* Non default ciphersuite */
3366         if (!TEST_true(SSL_set_ciphersuites(clientssl,
3367                                             "TLS_AES_128_CCM_SHA256")))
3368             goto end;
3369     }
3370
3371     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
3372         goto end;
3373
3374     testresult = 1;
3375
3376  end:
3377     SSL_free(serverssl);
3378     SSL_free(clientssl);
3379     SSL_CTX_free(sctx);
3380     SSL_CTX_free(cctx);
3381
3382     return testresult;
3383 }
3384
3385 static int test_ciphersuite_change(void)
3386 {
3387     SSL_CTX *cctx = NULL, *sctx = NULL;
3388     SSL *clientssl = NULL, *serverssl = NULL;
3389     SSL_SESSION *clntsess = NULL;
3390     int testresult = 0;
3391     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
3392
3393     /* Create a session based on SHA-256 */
3394     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3395                                        TLS1_VERSION, TLS_MAX_VERSION,
3396                                        &sctx, &cctx, cert, privkey))
3397             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
3398                                                    "TLS_AES_128_GCM_SHA256"))
3399             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3400                                           &clientssl, NULL, NULL))
3401             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3402                                                 SSL_ERROR_NONE)))
3403         goto end;
3404
3405     clntsess = SSL_get1_session(clientssl);
3406     /* Save for later */
3407     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
3408     SSL_shutdown(clientssl);
3409     SSL_shutdown(serverssl);
3410     SSL_free(serverssl);
3411     SSL_free(clientssl);
3412     serverssl = clientssl = NULL;
3413
3414 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3415     /* Check we can resume a session with a different SHA-256 ciphersuite */
3416     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3417                                             "TLS_CHACHA20_POLY1305_SHA256"))
3418             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3419                                              NULL, NULL))
3420             || !TEST_true(SSL_set_session(clientssl, clntsess))
3421             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3422                                                 SSL_ERROR_NONE))
3423             || !TEST_true(SSL_session_reused(clientssl)))
3424         goto end;
3425
3426     SSL_SESSION_free(clntsess);
3427     clntsess = SSL_get1_session(clientssl);
3428     SSL_shutdown(clientssl);
3429     SSL_shutdown(serverssl);
3430     SSL_free(serverssl);
3431     SSL_free(clientssl);
3432     serverssl = clientssl = NULL;
3433 # endif
3434
3435     /*
3436      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
3437      * succeeds but does not resume.
3438      */
3439     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
3440             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3441                                              NULL, NULL))
3442             || !TEST_true(SSL_set_session(clientssl, clntsess))
3443             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3444                                                 SSL_ERROR_SSL))
3445             || !TEST_false(SSL_session_reused(clientssl)))
3446         goto end;
3447
3448     SSL_SESSION_free(clntsess);
3449     clntsess = NULL;
3450     SSL_shutdown(clientssl);
3451     SSL_shutdown(serverssl);
3452     SSL_free(serverssl);
3453     SSL_free(clientssl);
3454     serverssl = clientssl = NULL;
3455
3456     /* Create a session based on SHA384 */
3457     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
3458             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3459                                           &clientssl, NULL, NULL))
3460             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3461                                                 SSL_ERROR_NONE)))
3462         goto end;
3463
3464     clntsess = SSL_get1_session(clientssl);
3465     SSL_shutdown(clientssl);
3466     SSL_shutdown(serverssl);
3467     SSL_free(serverssl);
3468     SSL_free(clientssl);
3469     serverssl = clientssl = NULL;
3470
3471     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3472                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
3473             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
3474                                                    "TLS_AES_256_GCM_SHA384"))
3475             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3476                                              NULL, NULL))
3477             || !TEST_true(SSL_set_session(clientssl, clntsess))
3478                /*
3479                 * We use SSL_ERROR_WANT_READ below so that we can pause the
3480                 * connection after the initial ClientHello has been sent to
3481                 * enable us to make some session changes.
3482                 */
3483             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3484                                                 SSL_ERROR_WANT_READ)))
3485         goto end;
3486
3487     /* Trick the client into thinking this session is for a different digest */
3488     clntsess->cipher = aes_128_gcm_sha256;
3489     clntsess->cipher_id = clntsess->cipher->id;
3490
3491     /*
3492      * Continue the previously started connection. Server has selected a SHA-384
3493      * ciphersuite, but client thinks the session is for SHA-256, so it should
3494      * bail out.
3495      */
3496     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
3497                                                 SSL_ERROR_SSL))
3498             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
3499                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
3500         goto end;
3501
3502     testresult = 1;
3503
3504  end:
3505     SSL_SESSION_free(clntsess);
3506     SSL_free(serverssl);
3507     SSL_free(clientssl);
3508     SSL_CTX_free(sctx);
3509     SSL_CTX_free(cctx);
3510
3511     return testresult;
3512 }
3513
3514 /*
3515  * Test TLSv1.3 Cipher Suite
3516  * Test 0 = Set TLS1.3 cipher on context
3517  * Test 1 = Set TLS1.3 cipher on SSL
3518  * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
3519  * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
3520  */
3521 static int test_tls13_ciphersuite(int idx)
3522 {
3523     SSL_CTX *sctx = NULL, *cctx = NULL;
3524     SSL *serverssl = NULL, *clientssl = NULL;
3525     static const char *t13_ciphers[] = {
3526         TLS1_3_RFC_AES_128_GCM_SHA256,
3527         TLS1_3_RFC_AES_256_GCM_SHA384,
3528         TLS1_3_RFC_AES_128_CCM_SHA256,
3529 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3530         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
3531         TLS1_3_RFC_AES_256_GCM_SHA384 ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
3532 # endif
3533         TLS1_3_RFC_AES_128_CCM_8_SHA256 ":" TLS1_3_RFC_AES_128_CCM_SHA256
3534     };
3535     const char *t13_cipher = NULL;
3536     const char *t12_cipher = NULL;
3537     const char *negotiated_scipher;
3538     const char *negotiated_ccipher;
3539     int set_at_ctx = 0;
3540     int set_at_ssl = 0;
3541     int testresult = 0;
3542     int max_ver;
3543     size_t i;
3544
3545     switch (idx) {
3546         case 0:
3547             set_at_ctx = 1;
3548             break;
3549         case 1:
3550             set_at_ssl = 1;
3551             break;
3552         case 2:
3553             set_at_ctx = 1;
3554             t12_cipher = TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
3555             break;
3556         case 3:
3557             set_at_ssl = 1;
3558             t12_cipher = TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
3559             break;
3560     }
3561
3562     for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
3563 # ifdef OPENSSL_NO_TLS1_2
3564         if (max_ver == TLS1_2_VERSION)
3565             continue;
3566 # endif
3567         for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
3568             t13_cipher = t13_ciphers[i];
3569             if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
3570                                                TLS_client_method(),
3571                                                TLS1_VERSION, max_ver,
3572                                                &sctx, &cctx, cert, privkey)))
3573                 goto end;
3574
3575             if (set_at_ctx) {
3576                 if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
3577                     || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
3578                     goto end;
3579                 if (t12_cipher != NULL) {
3580                     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
3581                         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
3582                                                               t12_cipher)))
3583                         goto end;
3584                 }
3585             }
3586
3587             if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3588                                               &clientssl, NULL, NULL)))
3589                 goto end;
3590
3591             if (set_at_ssl) {
3592                 if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
3593                     || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
3594                     goto end;
3595                 if (t12_cipher != NULL) {
3596                     if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
3597                         || !TEST_true(SSL_set_cipher_list(clientssl,
3598                                                           t12_cipher)))
3599                         goto end;
3600                 }
3601             }
3602
3603             if (!TEST_true(create_ssl_connection(serverssl, clientssl,
3604                                                  SSL_ERROR_NONE)))
3605                 goto end;
3606
3607             negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
3608                                                                  serverssl));
3609             negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
3610                                                                  clientssl));
3611             if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
3612                 goto end;
3613
3614             /*
3615              * TEST_strn_eq is used below because t13_cipher can contain
3616              * multiple ciphersuites
3617              */
3618             if (max_ver == TLS1_3_VERSION
3619                 && !TEST_strn_eq(t13_cipher, negotiated_scipher,
3620                                  strlen(negotiated_scipher)))
3621                 goto end;
3622
3623 # ifndef OPENSSL_NO_TLS1_2
3624             /* Below validation is not done when t12_cipher is NULL */
3625             if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
3626                 && !TEST_str_eq(t12_cipher, negotiated_scipher))
3627                 goto end;
3628 # endif
3629
3630             SSL_free(serverssl);
3631             serverssl = NULL;
3632             SSL_free(clientssl);
3633             clientssl = NULL;
3634             SSL_CTX_free(sctx);
3635             sctx = NULL;
3636             SSL_CTX_free(cctx);
3637             cctx = NULL;
3638         }
3639     }
3640
3641     testresult = 1;
3642  end:
3643     SSL_free(serverssl);
3644     SSL_free(clientssl);
3645     SSL_CTX_free(sctx);
3646     SSL_CTX_free(cctx);
3647     return testresult;
3648 }
3649
3650 /*
3651  * Test TLSv1.3 PSKs
3652  * Test 0 = Test new style callbacks
3653  * Test 1 = Test both new and old style callbacks
3654  * Test 2 = Test old style callbacks
3655  * Test 3 = Test old style callbacks with no certificate
3656  */
3657 static int test_tls13_psk(int idx)
3658 {
3659     SSL_CTX *sctx = NULL, *cctx = NULL;
3660     SSL *serverssl = NULL, *clientssl = NULL;
3661     const SSL_CIPHER *cipher = NULL;
3662     const unsigned char key[] = {
3663         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
3664         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3665         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
3666         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
3667     };
3668     int testresult = 0;
3669
3670     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3671                                        TLS1_VERSION, TLS_MAX_VERSION,
3672                                        &sctx, &cctx, idx == 3 ? NULL : cert,
3673                                        idx == 3 ? NULL : privkey)))
3674         goto end;
3675
3676     if (idx != 3) {
3677         /*
3678          * We use a ciphersuite with SHA256 to ease testing old style PSK
3679          * callbacks which will always default to SHA256. This should not be
3680          * necessary if we have no cert/priv key. In that case the server should
3681          * prefer SHA256 automatically.
3682          */
3683         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3684                                                 "TLS_AES_128_GCM_SHA256")))
3685             goto end;
3686     }
3687
3688     /*
3689      * Test 0: New style callbacks only
3690      * Test 1: New and old style callbacks (only the new ones should be used)
3691      * Test 2: Old style callbacks only
3692      */
3693     if (idx == 0 || idx == 1) {
3694         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
3695         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
3696     }
3697 #ifndef OPENSSL_NO_PSK
3698     if (idx >= 1) {
3699         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
3700         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
3701     }
3702 #endif
3703     srvid = pskid;
3704     use_session_cb_cnt = 0;
3705     find_session_cb_cnt = 0;
3706     psk_client_cb_cnt = 0;
3707     psk_server_cb_cnt = 0;
3708
3709     if (idx != 3) {
3710         /*
3711          * Check we can create a connection if callback decides not to send a
3712          * PSK
3713          */
3714         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3715                                                  NULL, NULL))
3716                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
3717                                                     SSL_ERROR_NONE))
3718                 || !TEST_false(SSL_session_reused(clientssl))
3719                 || !TEST_false(SSL_session_reused(serverssl)))
3720             goto end;
3721
3722         if (idx == 0 || idx == 1) {
3723             if (!TEST_true(use_session_cb_cnt == 1)
3724                     || !TEST_true(find_session_cb_cnt == 0)
3725                        /*
3726                         * If no old style callback then below should be 0
3727                         * otherwise 1
3728                         */
3729                     || !TEST_true(psk_client_cb_cnt == idx)
3730                     || !TEST_true(psk_server_cb_cnt == 0))
3731                 goto end;
3732         } else {
3733             if (!TEST_true(use_session_cb_cnt == 0)
3734                     || !TEST_true(find_session_cb_cnt == 0)
3735                     || !TEST_true(psk_client_cb_cnt == 1)
3736                     || !TEST_true(psk_server_cb_cnt == 0))
3737                 goto end;
3738         }
3739
3740         shutdown_ssl_connection(serverssl, clientssl);
3741         serverssl = clientssl = NULL;
3742         use_session_cb_cnt = psk_client_cb_cnt = 0;
3743     }
3744
3745     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3746                                              NULL, NULL)))
3747         goto end;
3748
3749     /* Create the PSK */
3750     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
3751     clientpsk = SSL_SESSION_new();
3752     if (!TEST_ptr(clientpsk)
3753             || !TEST_ptr(cipher)
3754             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
3755                                                       sizeof(key)))
3756             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
3757             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
3758                                                            TLS1_3_VERSION))
3759             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
3760         goto end;
3761     serverpsk = clientpsk;
3762
3763     /* Check we can create a connection and the PSK is used */
3764     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3765             || !TEST_true(SSL_session_reused(clientssl))
3766             || !TEST_true(SSL_session_reused(serverssl)))
3767         goto end;
3768
3769     if (idx == 0 || idx == 1) {
3770         if (!TEST_true(use_session_cb_cnt == 1)
3771                 || !TEST_true(find_session_cb_cnt == 1)
3772                 || !TEST_true(psk_client_cb_cnt == 0)
3773                 || !TEST_true(psk_server_cb_cnt == 0))
3774             goto end;
3775     } else {
3776         if (!TEST_true(use_session_cb_cnt == 0)
3777                 || !TEST_true(find_session_cb_cnt == 0)
3778                 || !TEST_true(psk_client_cb_cnt == 1)
3779                 || !TEST_true(psk_server_cb_cnt == 1))
3780             goto end;
3781     }
3782
3783     shutdown_ssl_connection(serverssl, clientssl);
3784     serverssl = clientssl = NULL;
3785     use_session_cb_cnt = find_session_cb_cnt = 0;
3786     psk_client_cb_cnt = psk_server_cb_cnt = 0;
3787
3788     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3789                                              NULL, NULL)))
3790         goto end;
3791
3792     /* Force an HRR */
3793     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
3794         goto end;
3795
3796     /*
3797      * Check we can create a connection, the PSK is used and the callbacks are
3798      * called twice.
3799      */
3800     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3801             || !TEST_true(SSL_session_reused(clientssl))
3802             || !TEST_true(SSL_session_reused(serverssl)))
3803         goto end;
3804
3805     if (idx == 0 || idx == 1) {
3806         if (!TEST_true(use_session_cb_cnt == 2)
3807                 || !TEST_true(find_session_cb_cnt == 2)
3808                 || !TEST_true(psk_client_cb_cnt == 0)
3809                 || !TEST_true(psk_server_cb_cnt == 0))
3810             goto end;
3811     } else {
3812         if (!TEST_true(use_session_cb_cnt == 0)
3813                 || !TEST_true(find_session_cb_cnt == 0)
3814                 || !TEST_true(psk_client_cb_cnt == 2)
3815                 || !TEST_true(psk_server_cb_cnt == 2))
3816             goto end;
3817     }
3818
3819     shutdown_ssl_connection(serverssl, clientssl);
3820     serverssl = clientssl = NULL;
3821     use_session_cb_cnt = find_session_cb_cnt = 0;
3822     psk_client_cb_cnt = psk_server_cb_cnt = 0;
3823
3824     if (idx != 3) {
3825         /*
3826          * Check that if the server rejects the PSK we can still connect, but with
3827          * a full handshake
3828          */
3829         srvid = "Dummy Identity";
3830         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3831                                                  NULL, NULL))
3832                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
3833                                                     SSL_ERROR_NONE))
3834                 || !TEST_false(SSL_session_reused(clientssl))
3835                 || !TEST_false(SSL_session_reused(serverssl)))
3836             goto end;
3837
3838         if (idx == 0 || idx == 1) {
3839             if (!TEST_true(use_session_cb_cnt == 1)
3840                     || !TEST_true(find_session_cb_cnt == 1)
3841                     || !TEST_true(psk_client_cb_cnt == 0)
3842                        /*
3843                         * If no old style callback then below should be 0
3844                         * otherwise 1
3845                         */
3846                     || !TEST_true(psk_server_cb_cnt == idx))
3847                 goto end;
3848         } else {
3849             if (!TEST_true(use_session_cb_cnt == 0)
3850                     || !TEST_true(find_session_cb_cnt == 0)
3851                     || !TEST_true(psk_client_cb_cnt == 1)
3852                     || !TEST_true(psk_server_cb_cnt == 1))
3853                 goto end;
3854         }
3855
3856         shutdown_ssl_connection(serverssl, clientssl);
3857         serverssl = clientssl = NULL;
3858     }
3859     testresult = 1;
3860
3861  end:
3862     SSL_SESSION_free(clientpsk);
3863     SSL_SESSION_free(serverpsk);
3864     clientpsk = serverpsk = NULL;
3865     SSL_free(serverssl);
3866     SSL_free(clientssl);
3867     SSL_CTX_free(sctx);
3868     SSL_CTX_free(cctx);
3869     return testresult;
3870 }
3871
3872 static unsigned char cookie_magic_value[] = "cookie magic";
3873
3874 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
3875                                     unsigned int *cookie_len)
3876 {
3877     /*
3878      * Not suitable as a real cookie generation function but good enough for
3879      * testing!
3880      */
3881     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
3882     *cookie_len = sizeof(cookie_magic_value) - 1;
3883
3884     return 1;
3885 }
3886
3887 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
3888                                   unsigned int cookie_len)
3889 {
3890     if (cookie_len == sizeof(cookie_magic_value) - 1
3891         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
3892         return 1;
3893
3894     return 0;
3895 }
3896
3897 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
3898                                         size_t *cookie_len)
3899 {
3900     unsigned int temp;
3901     int res = generate_cookie_callback(ssl, cookie, &temp);
3902     *cookie_len = temp;
3903     return res;
3904 }
3905
3906 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
3907                                       size_t cookie_len)
3908 {
3909     return verify_cookie_callback(ssl, cookie, cookie_len);
3910 }
3911
3912 static int test_stateless(void)
3913 {
3914     SSL_CTX *sctx = NULL, *cctx = NULL;
3915     SSL *serverssl = NULL, *clientssl = NULL;
3916     int testresult = 0;
3917
3918     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3919                                        TLS1_VERSION, TLS_MAX_VERSION,
3920                                        &sctx, &cctx, cert, privkey)))
3921         goto end;
3922
3923     /* The arrival of CCS messages can confuse the test */
3924     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
3925
3926     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3927                                       NULL, NULL))
3928                /* Send the first ClientHello */
3929             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3930                                                  SSL_ERROR_WANT_READ))
3931                /*
3932                 * This should fail with a -1 return because we have no callbacks
3933                 * set up
3934                 */
3935             || !TEST_int_eq(SSL_stateless(serverssl), -1))
3936         goto end;
3937
3938     /* Fatal error so abandon the connection from this client */
3939     SSL_free(clientssl);
3940     clientssl = NULL;
3941
3942     /* Set up the cookie generation and verification callbacks */
3943     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
3944     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
3945
3946     /*
3947      * Create a new connection from the client (we can reuse the server SSL
3948      * object).
3949      */
3950     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3951                                              NULL, NULL))
3952                /* Send the first ClientHello */
3953             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3954                                                 SSL_ERROR_WANT_READ))
3955                /* This should fail because there is no cookie */
3956             || !TEST_int_eq(SSL_stateless(serverssl), 0))
3957         goto end;
3958
3959     /* Abandon the connection from this client */
3960     SSL_free(clientssl);
3961     clientssl = NULL;
3962
3963     /*
3964      * Now create a connection from a new client but with the same server SSL
3965      * object
3966      */
3967     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3968                                              NULL, NULL))
3969                /* Send the first ClientHello */
3970             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3971                                                 SSL_ERROR_WANT_READ))
3972                /* This should fail because there is no cookie */
3973             || !TEST_int_eq(SSL_stateless(serverssl), 0)
3974                /* Send the second ClientHello */
3975             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3976                                                 SSL_ERROR_WANT_READ))
3977                /* This should succeed because a cookie is now present */
3978             || !TEST_int_eq(SSL_stateless(serverssl), 1)
3979                /* Complete the connection */
3980             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3981                                                 SSL_ERROR_NONE)))
3982         goto end;
3983
3984     shutdown_ssl_connection(serverssl, clientssl);
3985     serverssl = clientssl = NULL;
3986     testresult = 1;
3987
3988  end:
3989     SSL_free(serverssl);
3990     SSL_free(clientssl);
3991     SSL_CTX_free(sctx);
3992     SSL_CTX_free(cctx);
3993     return testresult;
3994
3995 }
3996 #endif /* OPENSSL_NO_TLS1_3 */
3997
3998 static int clntaddoldcb = 0;
3999 static int clntparseoldcb = 0;
4000 static int srvaddoldcb = 0;
4001 static int srvparseoldcb = 0;
4002 static int clntaddnewcb = 0;
4003 static int clntparsenewcb = 0;
4004 static int srvaddnewcb = 0;
4005 static int srvparsenewcb = 0;
4006 static int snicb = 0;
4007
4008 #define TEST_EXT_TYPE1  0xff00
4009
4010 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
4011                       size_t *outlen, int *al, void *add_arg)
4012 {
4013     int *server = (int *)add_arg;
4014     unsigned char *data;
4015
4016     if (SSL_is_server(s))
4017         srvaddoldcb++;
4018     else
4019         clntaddoldcb++;
4020
4021     if (*server != SSL_is_server(s)
4022             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
4023         return -1;
4024
4025     *data = 1;
4026     *out = data;
4027     *outlen = sizeof(char);
4028     return 1;
4029 }
4030
4031 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
4032                         void *add_arg)
4033 {
4034     OPENSSL_free((unsigned char *)out);
4035 }
4036
4037 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
4038                         size_t inlen, int *al, void *parse_arg)
4039 {
4040     int *server = (int *)parse_arg;
4041
4042     if (SSL_is_server(s))
4043         srvparseoldcb++;
4044     else
4045         clntparseoldcb++;
4046
4047     if (*server != SSL_is_server(s)
4048             || inlen != sizeof(char)
4049             || *in != 1)
4050         return -1;
4051
4052     return 1;
4053 }
4054
4055 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
4056                       const unsigned char **out, size_t *outlen, X509 *x,
4057                       size_t chainidx, int *al, void *add_arg)
4058 {
4059     int *server = (int *)add_arg;
4060     unsigned char *data;
4061
4062     if (SSL_is_server(s))
4063         srvaddnewcb++;
4064     else
4065         clntaddnewcb++;
4066
4067     if (*server != SSL_is_server(s)
4068             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
4069         return -1;
4070
4071     *data = 1;
4072     *out = data;
4073     *outlen = sizeof(*data);
4074     return 1;
4075 }
4076
4077 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
4078                         const unsigned char *out, void *add_arg)
4079 {
4080     OPENSSL_free((unsigned char *)out);
4081 }
4082
4083 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
4084                         const unsigned char *in, size_t inlen, X509 *x,
4085                         size_t chainidx, int *al, void *parse_arg)
4086 {
4087     int *server = (int *)parse_arg;
4088
4089     if (SSL_is_server(s))
4090         srvparsenewcb++;
4091     else
4092         clntparsenewcb++;
4093
4094     if (*server != SSL_is_server(s)
4095             || inlen != sizeof(char) || *in != 1)
4096         return -1;
4097
4098     return 1;
4099 }
4100
4101 static int sni_cb(SSL *s, int *al, void *arg)
4102 {
4103     SSL_CTX *ctx = (SSL_CTX *)arg;
4104
4105     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
4106         *al = SSL_AD_INTERNAL_ERROR;
4107         return SSL_TLSEXT_ERR_ALERT_FATAL;
4108     }
4109     snicb++;
4110     return SSL_TLSEXT_ERR_OK;
4111 }
4112
4113 /*
4114  * Custom call back tests.
4115  * Test 0: Old style callbacks in TLSv1.2
4116  * Test 1: New style callbacks in TLSv1.2
4117  * Test 2: New style callbacks in TLSv1.2 with SNI
4118  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
4119  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
4120  */
4121 static int test_custom_exts(int tst)
4122 {
4123     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
4124     SSL *clientssl = NULL, *serverssl = NULL;
4125     int testresult = 0;
4126     static int server = 1;
4127     static int client = 0;
4128     SSL_SESSION *sess = NULL;
4129     unsigned int context;
4130
4131 #if defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_3)
4132     /* Skip tests for TLSv1.2 and below in this case */
4133     if (tst < 3)
4134         return 1;
4135 #endif
4136
4137     /* Reset callback counters */
4138     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
4139     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
4140     snicb = 0;
4141
4142     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4143                                        TLS1_VERSION, TLS_MAX_VERSION,
4144                                        &sctx, &cctx, cert, privkey)))
4145         goto end;
4146
4147     if (tst == 2
4148             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL,
4149                                               TLS1_VERSION, TLS_MAX_VERSION,
4150                                               &sctx2, NULL, cert, privkey)))
4151         goto end;
4152
4153
4154     if (tst < 3) {
4155         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
4156         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
4157         if (sctx2 != NULL)
4158             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
4159     }
4160
4161     if (tst == 4) {
4162         context = SSL_EXT_CLIENT_HELLO
4163                   | SSL_EXT_TLS1_2_SERVER_HELLO
4164                   | SSL_EXT_TLS1_3_SERVER_HELLO
4165                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
4166                   | SSL_EXT_TLS1_3_CERTIFICATE
4167                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
4168     } else {
4169         context = SSL_EXT_CLIENT_HELLO
4170                   | SSL_EXT_TLS1_2_SERVER_HELLO
4171                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
4172     }
4173
4174     /* Create a client side custom extension */
4175     if (tst == 0) {
4176         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
4177                                                      old_add_cb, old_free_cb,
4178                                                      &client, old_parse_cb,
4179                                                      &client)))
4180             goto end;
4181     } else {
4182         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
4183                                               new_add_cb, new_free_cb,
4184                                               &client, new_parse_cb, &client)))
4185             goto end;
4186     }
4187
4188     /* Should not be able to add duplicates */
4189     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
4190                                                   old_add_cb, old_free_cb,
4191                                                   &client, old_parse_cb,
4192                                                   &client))
4193             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
4194                                                   context, new_add_cb,
4195                                                   new_free_cb, &client,
4196                                                   new_parse_cb, &client)))
4197         goto end;
4198
4199     /* Create a server side custom extension */
4200     if (tst == 0) {
4201         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
4202                                                      old_add_cb, old_free_cb,
4203                                                      &server, old_parse_cb,
4204                                                      &server)))
4205             goto end;
4206     } else {
4207         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
4208                                               new_add_cb, new_free_cb,
4209                                               &server, new_parse_cb, &server)))
4210             goto end;
4211         if (sctx2 != NULL
4212                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
4213                                                      context, new_add_cb,
4214                                                      new_free_cb, &server,
4215                                                      new_parse_cb, &server)))
4216             goto end;
4217     }
4218
4219     /* Should not be able to add duplicates */
4220     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
4221                                                   old_add_cb, old_free_cb,
4222                                                   &server, old_parse_cb,
4223                                                   &server))
4224             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
4225                                                   context, new_add_cb,
4226                                                   new_free_cb, &server,
4227                                                   new_parse_cb, &server)))
4228         goto end;
4229
4230     if (tst == 2) {
4231         /* Set up SNI */
4232         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
4233                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
4234             goto end;
4235     }
4236
4237     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4238                                       &clientssl, NULL, NULL))
4239             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4240                                                 SSL_ERROR_NONE)))
4241         goto end;
4242
4243     if (tst == 0) {
4244         if (clntaddoldcb != 1
4245                 || clntparseoldcb != 1
4246                 || srvaddoldcb != 1
4247                 || srvparseoldcb != 1)
4248             goto end;
4249     } else if (tst == 1 || tst == 2 || tst == 3) {
4250         if (clntaddnewcb != 1
4251                 || clntparsenewcb != 1
4252                 || srvaddnewcb != 1
4253                 || srvparsenewcb != 1
4254                 || (tst != 2 && snicb != 0)
4255                 || (tst == 2 && snicb != 1))
4256             goto end;
4257     } else {
4258         /* In this case there 2 NewSessionTicket messages created */
4259         if (clntaddnewcb != 1
4260                 || clntparsenewcb != 5
4261                 || srvaddnewcb != 5
4262                 || srvparsenewcb != 1)
4263             goto end;
4264     }
4265
4266     sess = SSL_get1_session(clientssl);
4267     SSL_shutdown(clientssl);
4268     SSL_shutdown(serverssl);
4269     SSL_free(serverssl);
4270     SSL_free(clientssl);
4271     serverssl = clientssl = NULL;
4272
4273     if (tst == 3) {
4274         /* We don't bother with the resumption aspects for this test */
4275         testresult = 1;
4276         goto end;
4277     }
4278
4279     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4280                                       NULL, NULL))
4281             || !TEST_true(SSL_set_session(clientssl, sess))
4282             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4283                                                SSL_ERROR_NONE)))
4284         goto end;
4285
4286     /*
4287      * For a resumed session we expect to add the ClientHello extension. For the
4288      * old style callbacks we ignore it on the server side because they set
4289      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
4290      * them.
4291      */
4292     if (tst == 0) {
4293         if (clntaddoldcb != 2
4294                 || clntparseoldcb != 1
4295                 || srvaddoldcb != 1
4296                 || srvparseoldcb != 1)
4297             goto end;
4298     } else if (tst == 1 || tst == 2 || tst == 3) {
4299         if (clntaddnewcb != 2
4300                 || clntparsenewcb != 2
4301                 || srvaddnewcb != 2
4302                 || srvparsenewcb != 2)
4303             goto end;
4304     } else {
4305         /*
4306          * No Certificate message extensions in the resumption handshake,
4307          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
4308          */
4309         if (clntaddnewcb != 2
4310                 || clntparsenewcb != 8
4311                 || srvaddnewcb != 8
4312                 || srvparsenewcb != 2)
4313             goto end;
4314     }
4315
4316     testresult = 1;
4317
4318 end:
4319     SSL_SESSION_free(sess);
4320     SSL_free(serverssl);
4321     SSL_free(clientssl);
4322     SSL_CTX_free(sctx2);
4323     SSL_CTX_free(sctx);
4324     SSL_CTX_free(cctx);
4325     return testresult;
4326 }
4327
4328 /*
4329  * Test loading of serverinfo data in various formats. test_sslmessages actually
4330  * tests to make sure the extensions appear in the handshake
4331  */
4332 static int test_serverinfo(int tst)
4333 {
4334     unsigned int version;
4335     unsigned char *sibuf;
4336     size_t sibuflen;
4337     int ret, expected, testresult = 0;
4338     SSL_CTX *ctx;
4339
4340     ctx = SSL_CTX_new(TLS_method());
4341     if (!TEST_ptr(ctx))
4342         goto end;
4343
4344     if ((tst & 0x01) == 0x01)
4345         version = SSL_SERVERINFOV2;
4346     else
4347         version = SSL_SERVERINFOV1;
4348
4349     if ((tst & 0x02) == 0x02) {
4350         sibuf = serverinfov2;
4351         sibuflen = sizeof(serverinfov2);
4352         expected = (version == SSL_SERVERINFOV2);
4353     } else {
4354         sibuf = serverinfov1;
4355         sibuflen = sizeof(serverinfov1);
4356         expected = (version == SSL_SERVERINFOV1);
4357     }
4358
4359     if ((tst & 0x04) == 0x04) {
4360         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
4361     } else {
4362         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
4363
4364         /*
4365          * The version variable is irrelevant in this case - it's what is in the
4366          * buffer that matters
4367          */
4368         if ((tst & 0x02) == 0x02)
4369             expected = 0;
4370         else
4371             expected = 1;
4372     }
4373
4374     if (!TEST_true(ret == expected))
4375         goto end;
4376
4377     testresult = 1;
4378
4379  end:
4380     SSL_CTX_free(ctx);
4381
4382     return testresult;
4383 }
4384
4385 /*
4386  * Test that SSL_export_keying_material() produces expected results. There are
4387  * no test vectors so all we do is test that both sides of the communication
4388  * produce the same results for different protocol versions.
4389  */
4390 #define SMALL_LABEL_LEN 10
4391 #define LONG_LABEL_LEN  249
4392 static int test_export_key_mat(int tst)
4393 {
4394     int testresult = 0;
4395     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
4396     SSL *clientssl = NULL, *serverssl = NULL;
4397     const char label[LONG_LABEL_LEN + 1] = "test label";
4398     const unsigned char context[] = "context";
4399     const unsigned char *emptycontext = NULL;
4400     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
4401     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
4402     size_t labellen;
4403     const int protocols[] = {
4404         TLS1_VERSION,
4405         TLS1_1_VERSION,
4406         TLS1_2_VERSION,
4407         TLS1_3_VERSION,
4408         TLS1_3_VERSION,
4409         TLS1_3_VERSION
4410     };
4411
4412 #ifdef OPENSSL_NO_TLS1
4413     if (tst == 0)
4414         return 1;
4415 #endif
4416 #ifdef OPENSSL_NO_TLS1_1
4417     if (tst == 1)
4418         return 1;
4419 #endif
4420 #ifdef OPENSSL_NO_TLS1_2
4421     if (tst == 2)
4422         return 1;
4423 #endif
4424 #ifdef OPENSSL_NO_TLS1_3
4425     if (tst >= 3)
4426         return 1;
4427 #endif
4428     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4429                                        TLS1_VERSION, TLS_MAX_VERSION,
4430                                        &sctx, &cctx, cert, privkey)))
4431         goto end;
4432
4433     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
4434     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
4435     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
4436
4437     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
4438                                       NULL)))
4439         goto end;
4440
4441     /*
4442      * Premature call of SSL_export_keying_material should just fail.
4443      */
4444     if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
4445                                                 sizeof(ckeymat1), label,
4446                                                 SMALL_LABEL_LEN + 1, context,
4447                                                 sizeof(context) - 1, 1), 0))
4448         goto end;
4449
4450     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4451                                          SSL_ERROR_NONE)))
4452         goto end;
4453
4454     if (tst == 5) {
4455         /*
4456          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
4457          * go over that.
4458          */
4459         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
4460                                                     sizeof(ckeymat1), label,
4461                                                     LONG_LABEL_LEN + 1, context,
4462                                                     sizeof(context) - 1, 1), 0))
4463             goto end;
4464
4465         testresult = 1;
4466         goto end;
4467     } else if (tst == 4) {
4468         labellen = LONG_LABEL_LEN;
4469     } else {
4470         labellen = SMALL_LABEL_LEN;
4471     }
4472
4473     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
4474                                                 sizeof(ckeymat1), label,
4475                                                 labellen, context,
4476                                                 sizeof(context) - 1, 1), 1)
4477             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
4478                                                        sizeof(ckeymat2), label,
4479                                                        labellen,
4480                                                        emptycontext,
4481                                                        0, 1), 1)
4482             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
4483                                                        sizeof(ckeymat3), label,
4484                                                        labellen,
4485                                                        NULL, 0, 0), 1)
4486             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
4487                                                        sizeof(skeymat1), label,
4488                                                        labellen,
4489                                                        context,
4490                                                        sizeof(context) -1, 1),
4491                             1)
4492             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
4493                                                        sizeof(skeymat2), label,
4494                                                        labellen,
4495                                                        emptycontext,
4496                                                        0, 1), 1)
4497             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
4498                                                        sizeof(skeymat3), label,
4499                                                        labellen,
4500                                                        NULL, 0, 0), 1)
4501                /*
4502                 * Check that both sides created the same key material with the
4503                 * same context.
4504                 */
4505             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
4506                             sizeof(skeymat1))
4507                /*
4508                 * Check that both sides created the same key material with an
4509                 * empty context.
4510                 */
4511             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
4512                             sizeof(skeymat2))
4513                /*
4514                 * Check that both sides created the same key material without a
4515                 * context.
4516                 */
4517             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
4518                             sizeof(skeymat3))
4519                /* Different contexts should produce different results */
4520             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
4521                             sizeof(ckeymat2)))
4522         goto end;
4523
4524     /*
4525      * Check that an empty context and no context produce different results in
4526      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
4527      */
4528     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
4529                                   sizeof(ckeymat3)))
4530             || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
4531                                          sizeof(ckeymat3))))
4532         goto end;
4533
4534     testresult = 1;
4535
4536  end:
4537     SSL_free(serverssl);
4538     SSL_free(clientssl);
4539     SSL_CTX_free(sctx2);
4540     SSL_CTX_free(sctx);
4541     SSL_CTX_free(cctx);
4542
4543     return testresult;
4544 }
4545
4546 #ifndef OPENSSL_NO_TLS1_3
4547 /*
4548  * Test that SSL_export_keying_material_early() produces expected
4549  * results. There are no test vectors so all we do is test that both
4550  * sides of the communication produce the same results for different
4551  * protocol versions.
4552  */
4553 static int test_export_key_mat_early(int idx)
4554 {
4555     static const char label[] = "test label";
4556     static const unsigned char context[] = "context";
4557     int testresult = 0;
4558     SSL_CTX *cctx = NULL, *sctx = NULL;
4559     SSL *clientssl = NULL, *serverssl = NULL;
4560     SSL_SESSION *sess = NULL;
4561     const unsigned char *emptycontext = NULL;
4562     unsigned char ckeymat1[80], ckeymat2[80];
4563     unsigned char skeymat1[80], skeymat2[80];
4564     unsigned char buf[1];
4565     size_t readbytes, written;
4566
4567     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
4568                                         &sess, idx)))
4569         goto end;
4570
4571     /* Here writing 0 length early data is enough. */
4572     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
4573             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4574                                                 &readbytes),
4575                             SSL_READ_EARLY_DATA_ERROR)
4576             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4577                             SSL_EARLY_DATA_ACCEPTED))
4578         goto end;
4579
4580     if (!TEST_int_eq(SSL_export_keying_material_early(
4581                      clientssl, ckeymat1, sizeof(ckeymat1), label,
4582                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
4583             || !TEST_int_eq(SSL_export_keying_material_early(
4584                             clientssl, ckeymat2, sizeof(ckeymat2), label,
4585                             sizeof(label) - 1, emptycontext, 0), 1)
4586             || !TEST_int_eq(SSL_export_keying_material_early(
4587                             serverssl, skeymat1, sizeof(skeymat1), label,
4588                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
4589             || !TEST_int_eq(SSL_export_keying_material_early(
4590                             serverssl, skeymat2, sizeof(skeymat2), label,
4591                             sizeof(label) - 1, emptycontext, 0), 1)
4592                /*
4593                 * Check that both sides created the same key material with the
4594                 * same context.
4595                 */
4596             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
4597                             sizeof(skeymat1))
4598                /*
4599                 * Check that both sides created the same key material with an
4600                 * empty context.
4601                 */
4602             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
4603                             sizeof(skeymat2))
4604                /* Different contexts should produce different results */
4605             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
4606                             sizeof(ckeymat2)))
4607         goto end;
4608
4609     testresult = 1;
4610
4611  end:
4612     SSL_SESSION_free(sess);
4613     SSL_SESSION_free(clientpsk);
4614     SSL_SESSION_free(serverpsk);
4615     clientpsk = serverpsk = NULL;
4616     SSL_free(serverssl);
4617     SSL_free(clientssl);
4618     SSL_CTX_free(sctx);
4619     SSL_CTX_free(cctx);
4620
4621     return testresult;
4622 }
4623
4624 #define NUM_KEY_UPDATE_MESSAGES 40
4625 /*
4626  * Test KeyUpdate.
4627  */
4628 static int test_key_update(void)
4629 {
4630     SSL_CTX *cctx = NULL, *sctx = NULL;
4631     SSL *clientssl = NULL, *serverssl = NULL;
4632     int testresult = 0, i, j;
4633     char buf[20];
4634     static char *mess = "A test message";
4635
4636     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4637                                        TLS_client_method(),
4638                                        TLS1_3_VERSION,
4639                                        0,
4640                                        &sctx, &cctx, cert, privkey))
4641             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4642                                              NULL, NULL))
4643             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4644                                                 SSL_ERROR_NONE)))
4645         goto end;
4646
4647     for (j = 0; j < 2; j++) {
4648         /* Send lots of KeyUpdate messages */
4649         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
4650             if (!TEST_true(SSL_key_update(clientssl,
4651                                           (j == 0)
4652                                           ? SSL_KEY_UPDATE_NOT_REQUESTED
4653                                           : SSL_KEY_UPDATE_REQUESTED))
4654                     || !TEST_true(SSL_do_handshake(clientssl)))
4655                 goto end;
4656         }
4657
4658         /* Check that sending and receiving app data is ok */
4659         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
4660                 || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
4661                                          strlen(mess)))
4662             goto end;
4663
4664         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
4665                 || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
4666                                          strlen(mess)))
4667             goto end;
4668     }
4669
4670     testresult = 1;
4671
4672  end:
4673     SSL_free(serverssl);
4674     SSL_free(clientssl);
4675     SSL_CTX_free(sctx);
4676     SSL_CTX_free(cctx);
4677
4678     return testresult;
4679 }
4680
4681 /*
4682  * Test we can handle a KeyUpdate (update requested) message while write data
4683  * is pending.
4684  * Test 0: Client sends KeyUpdate while Server is writing
4685  * Test 1: Server sends KeyUpdate while Client is writing
4686  */
4687 static int test_key_update_in_write(int tst)
4688 {
4689     SSL_CTX *cctx = NULL, *sctx = NULL;
4690     SSL *clientssl = NULL, *serverssl = NULL;
4691     int testresult = 0;
4692     char buf[20];
4693     static char *mess = "A test message";
4694     BIO *bretry = BIO_new(bio_s_always_retry());
4695     BIO *tmp = NULL;
4696     SSL *peerupdate = NULL, *peerwrite = NULL;
4697
4698     if (!TEST_ptr(bretry)
4699             || !TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4700                                               TLS_client_method(),
4701                                               TLS1_3_VERSION,
4702                                               0,
4703                                               &sctx, &cctx, cert, privkey))
4704             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4705                                              NULL, NULL))
4706             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4707                                                 SSL_ERROR_NONE)))
4708         goto end;
4709
4710     peerupdate = tst == 0 ? clientssl : serverssl;
4711     peerwrite = tst == 0 ? serverssl : clientssl;
4712
4713     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
4714             || !TEST_true(SSL_do_handshake(peerupdate)))
4715         goto end;
4716
4717     /* Swap the writing endpoint's write BIO to force a retry */
4718     tmp = SSL_get_wbio(peerwrite);
4719     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
4720         tmp = NULL;
4721         goto end;
4722     }
4723     SSL_set0_wbio(peerwrite, bretry);
4724     bretry = NULL;
4725
4726     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
4727     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
4728             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE))
4729         goto end;
4730
4731     /* Reinstate the original writing endpoint's write BIO */
4732     SSL_set0_wbio(peerwrite, tmp);
4733     tmp = NULL;
4734
4735     /* Now read some data - we will read the key update */
4736     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
4737             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ))
4738         goto end;
4739
4740     /*
4741      * Complete the write we started previously and read it from the other
4742      * endpoint
4743      */
4744     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
4745             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
4746         goto end;
4747
4748     /* Write more data to ensure we send the KeyUpdate message back */
4749     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
4750             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
4751         goto end;
4752
4753     testresult = 1;
4754
4755  end:
4756     SSL_free(serverssl);
4757     SSL_free(clientssl);
4758     SSL_CTX_free(sctx);
4759     SSL_CTX_free(cctx);
4760     BIO_free(bretry);
4761     BIO_free(tmp);
4762
4763     return testresult;
4764 }
4765 #endif /* OPENSSL_NO_TLS1_3 */
4766
4767 static int test_ssl_clear(int idx)
4768 {
4769     SSL_CTX *cctx = NULL, *sctx = NULL;
4770     SSL *clientssl = NULL, *serverssl = NULL;
4771     int testresult = 0;
4772
4773 #ifdef OPENSSL_NO_TLS1_2
4774     if (idx == 1)
4775         return 1;
4776 #endif
4777
4778     /* Create an initial connection */
4779     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4780                                        TLS1_VERSION, TLS_MAX_VERSION,
4781                                        &sctx, &cctx, cert, privkey))
4782             || (idx == 1
4783                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
4784                                                             TLS1_2_VERSION)))
4785             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4786                                           &clientssl, NULL, NULL))
4787             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4788                                                 SSL_ERROR_NONE)))
4789         goto end;
4790
4791     SSL_shutdown(clientssl);
4792     SSL_shutdown(serverssl);
4793     SSL_free(serverssl);
4794     serverssl = NULL;
4795
4796     /* Clear clientssl - we're going to reuse the object */
4797     if (!TEST_true(SSL_clear(clientssl)))
4798         goto end;
4799
4800     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4801                                              NULL, NULL))
4802             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4803                                                 SSL_ERROR_NONE))
4804             || !TEST_true(SSL_session_reused(clientssl)))
4805         goto end;
4806
4807     SSL_shutdown(clientssl);
4808     SSL_shutdown(serverssl);
4809
4810     testresult = 1;
4811
4812  end:
4813     SSL_free(serverssl);
4814     SSL_free(clientssl);
4815     SSL_CTX_free(sctx);
4816     SSL_CTX_free(cctx);
4817
4818     return testresult;
4819 }
4820
4821 /* Parse CH and retrieve any MFL extension value if present */
4822 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
4823 {
4824     long len;
4825     unsigned char *data;
4826     PACKET pkt = {0}, pkt2 = {0}, pkt3 = {0};
4827     unsigned int MFL_code = 0, type = 0;
4828
4829     if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
4830         goto end;
4831
4832     if (!TEST_true( PACKET_buf_init( &pkt, data, len ) )
4833                /* Skip the record header */
4834             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
4835                /* Skip the handshake message header */
4836             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
4837                /* Skip client version and random */
4838             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
4839                                                + SSL3_RANDOM_SIZE))
4840                /* Skip session id */
4841             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
4842                /* Skip ciphers */
4843             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
4844                /* Skip compression */
4845             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
4846                /* Extensions len */
4847             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
4848         goto end;
4849
4850     /* Loop through all extensions */
4851     while (PACKET_remaining(&pkt2)) {
4852         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
4853                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
4854             goto end;
4855
4856         if (type == TLSEXT_TYPE_max_fragment_length) {
4857             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
4858                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
4859                 goto end;
4860
4861             *mfl_codemfl_code = MFL_code;
4862             return 1;
4863         }
4864     }
4865
4866  end:
4867     return 0;
4868 }
4869
4870 /* Maximum-Fragment-Length TLS extension mode to test */
4871 static const unsigned char max_fragment_len_test[] = {
4872     TLSEXT_max_fragment_length_512,
4873     TLSEXT_max_fragment_length_1024,
4874     TLSEXT_max_fragment_length_2048,
4875     TLSEXT_max_fragment_length_4096
4876 };
4877
4878 static int test_max_fragment_len_ext(int idx_tst)
4879 {
4880     SSL_CTX *ctx;
4881     SSL *con = NULL;
4882     int testresult = 0, MFL_mode = 0;
4883     BIO *rbio, *wbio;
4884
4885     ctx = SSL_CTX_new(TLS_method());
4886     if (!TEST_ptr(ctx))
4887         goto end;
4888
4889     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
4890                    ctx, max_fragment_len_test[idx_tst])))
4891         goto end;
4892
4893     con = SSL_new(ctx);
4894     if (!TEST_ptr(con))
4895         goto end;
4896
4897     rbio = BIO_new(BIO_s_mem());
4898     wbio = BIO_new(BIO_s_mem());
4899     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
4900         BIO_free(rbio);
4901         BIO_free(wbio);
4902         goto end;
4903     }
4904
4905     SSL_set_bio(con, rbio, wbio);
4906     SSL_set_connect_state(con);
4907
4908     if (!TEST_int_le(SSL_connect(con), 0)) {
4909         /* This shouldn't succeed because we don't have a server! */
4910         goto end;
4911     }
4912
4913     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
4914         /* no MFL in client hello */
4915         goto end;
4916     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
4917         goto end;
4918
4919     testresult = 1;
4920
4921 end:
4922     SSL_free(con);
4923     SSL_CTX_free(ctx);
4924
4925     return testresult;
4926 }
4927
4928 #ifndef OPENSSL_NO_TLS1_3
4929 static int test_pha_key_update(void)
4930 {
4931     SSL_CTX *cctx = NULL, *sctx = NULL;
4932     SSL *clientssl = NULL, *serverssl = NULL;
4933     int testresult = 0;
4934
4935     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4936                                        TLS1_VERSION, TLS_MAX_VERSION,
4937                                        &sctx, &cctx, cert, privkey)))
4938         return 0;
4939
4940     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
4941         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
4942         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
4943         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
4944         goto end;
4945
4946     SSL_CTX_set_post_handshake_auth(cctx, 1);
4947
4948     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4949                                       NULL, NULL)))
4950         goto end;
4951
4952     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4953                                          SSL_ERROR_NONE)))
4954         goto end;
4955
4956     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
4957     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
4958         goto end;
4959
4960     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
4961         goto end;
4962
4963     /* Start handshake on the server */
4964     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
4965         goto end;
4966
4967     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
4968     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4969                                          SSL_ERROR_NONE)))
4970         goto end;
4971
4972     SSL_shutdown(clientssl);
4973     SSL_shutdown(serverssl);
4974
4975     testresult = 1;
4976
4977  end:
4978     SSL_free(serverssl);
4979     SSL_free(clientssl);
4980     SSL_CTX_free(sctx);
4981     SSL_CTX_free(cctx);
4982     return testresult;
4983 }
4984 #endif
4985
4986 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
4987
4988 static SRP_VBASE *vbase = NULL;
4989
4990 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
4991 {
4992     int ret = SSL3_AL_FATAL;
4993     char *username;
4994     SRP_user_pwd *user = NULL;
4995
4996     username = SSL_get_srp_username(s);
4997     if (username == NULL) {
4998         *ad = SSL_AD_INTERNAL_ERROR;
4999         goto err;
5000     }
5001
5002     user = SRP_VBASE_get1_by_user(vbase, username);
5003     if (user == NULL) {
5004         *ad = SSL_AD_INTERNAL_ERROR;
5005         goto err;
5006     }
5007
5008     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
5009                                  user->info) <= 0) {
5010         *ad = SSL_AD_INTERNAL_ERROR;
5011         goto err;
5012     }
5013
5014     ret = 0;
5015
5016  err:
5017     SRP_user_pwd_free(user);
5018     return ret;
5019 }
5020
5021 static int create_new_vfile(char *userid, char *password, const char *filename)
5022 {
5023     char *gNid = NULL;
5024     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
5025     TXT_DB *db = NULL;
5026     int ret = 0;
5027     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
5028     size_t i;
5029
5030     if (!TEST_ptr(dummy) || !TEST_ptr(row))
5031         goto end;
5032
5033     gNid = SRP_create_verifier(userid, password, &row[DB_srpsalt],
5034                                &row[DB_srpverifier], NULL, NULL);
5035     if (!TEST_ptr(gNid))
5036         goto end;
5037
5038     /*
5039      * The only way to create an empty TXT_DB is to provide a BIO with no data
5040      * in it!
5041      */
5042     db = TXT_DB_read(dummy, DB_NUMBER);
5043     if (!TEST_ptr(db))
5044         goto end;
5045
5046     out = BIO_new_file(filename, "w");
5047     if (!TEST_ptr(out))
5048         goto end;
5049
5050     row[DB_srpid] = OPENSSL_strdup(userid);
5051     row[DB_srptype] = OPENSSL_strdup("V");
5052     row[DB_srpgN] = OPENSSL_strdup(gNid);
5053
5054     if (!TEST_ptr(row[DB_srpid])
5055             || !TEST_ptr(row[DB_srptype])
5056             || !TEST_ptr(row[DB_srpgN])
5057             || !TEST_true(TXT_DB_insert(db, row)))
5058         goto end;
5059
5060     row = NULL;
5061
5062     if (!TXT_DB_write(out, db))
5063         goto end;
5064
5065     ret = 1;
5066  end:
5067     if (row != NULL) {
5068         for (i = 0; i < DB_NUMBER; i++)
5069             OPENSSL_free(row[i]);
5070     }
5071     OPENSSL_free(row);
5072     BIO_free(dummy);
5073     BIO_free(out);
5074     TXT_DB_free(db);
5075
5076     return ret;
5077 }
5078
5079 static int create_new_vbase(char *userid, char *password)
5080 {
5081     BIGNUM *verifier = NULL, *salt = NULL;
5082     const SRP_gN *lgN = NULL;
5083     SRP_user_pwd *user_pwd = NULL;
5084     int ret = 0;
5085
5086     lgN = SRP_get_default_gN(NULL);
5087     if (!TEST_ptr(lgN))
5088         goto end;
5089
5090     if (!TEST_true(SRP_create_verifier_BN(userid, password, &salt, &verifier,
5091                                           lgN->N, lgN->g)))
5092         goto end;
5093
5094     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
5095     if (!TEST_ptr(user_pwd))
5096         goto end;
5097
5098     user_pwd->N = lgN->N;
5099     user_pwd->g = lgN->g;
5100     user_pwd->id = OPENSSL_strdup(userid);
5101     if (!TEST_ptr(user_pwd->id))
5102         goto end;
5103
5104     user_pwd->v = verifier;
5105     user_pwd->s = salt;
5106     verifier = salt = NULL;
5107
5108     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
5109         goto end;
5110     user_pwd = NULL;
5111
5112     ret = 1;
5113 end:
5114     SRP_user_pwd_free(user_pwd);
5115     BN_free(salt);
5116     BN_free(verifier);
5117
5118     return ret;
5119 }
5120
5121 /*
5122  * SRP tests
5123  *
5124  * Test 0: Simple successful SRP connection, new vbase
5125  * Test 1: Connection failure due to bad password, new vbase
5126  * Test 2: Simple successful SRP connection, vbase loaded from existing file
5127  * Test 3: Connection failure due to bad password, vbase loaded from existing
5128  *         file
5129  * Test 4: Simple successful SRP connection, vbase loaded from new file
5130  * Test 5: Connection failure due to bad password, vbase loaded from new file
5131  */
5132 static int test_srp(int tst)
5133 {
5134     char *userid = "test", *password = "password", *tstsrpfile;
5135     SSL_CTX *cctx = NULL, *sctx = NULL;
5136     SSL *clientssl = NULL, *serverssl = NULL;
5137     int ret, testresult = 0;
5138
5139     vbase = SRP_VBASE_new(NULL);
5140     if (!TEST_ptr(vbase))
5141         goto end;
5142
5143     if (tst == 0 || tst == 1) {
5144         if (!TEST_true(create_new_vbase(userid, password)))
5145             goto end;
5146     } else {
5147         if (tst == 4 || tst == 5) {
5148             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
5149                 goto end;
5150             tstsrpfile = tmpfilename;
5151         } else {
5152             tstsrpfile = srpvfile;
5153         }
5154         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
5155             goto end;
5156     }
5157
5158     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
5159                                        TLS1_VERSION, TLS_MAX_VERSION,
5160                                        &sctx, &cctx, cert, privkey)))
5161         goto end;
5162
5163     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
5164             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
5165             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
5166             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
5167             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
5168         goto end;
5169
5170     if (tst % 2 == 1) {
5171         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
5172             goto end;
5173     } else {
5174         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
5175             goto end;
5176     }
5177
5178     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5179                                       NULL, NULL)))
5180         goto end;
5181
5182     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
5183     if (ret) {
5184         if (!TEST_true(tst % 2 == 0))
5185             goto end;
5186     } else {
5187         if (!TEST_true(tst % 2 == 1))
5188             goto end;
5189     }
5190
5191     testresult = 1;
5192
5193  end:
5194     SRP_VBASE_free(vbase);
5195     vbase = NULL;
5196     SSL_free(serverssl);
5197     SSL_free(clientssl);
5198     SSL_CTX_free(sctx);
5199     SSL_CTX_free(cctx);
5200
5201     return testresult;
5202 }
5203 #endif
5204
5205 static int info_cb_failed = 0;
5206 static int info_cb_offset = 0;
5207 static int info_cb_this_state = -1;
5208
5209 static struct info_cb_states_st {
5210     int where;
5211     const char *statestr;
5212 } info_cb_states[][60] = {
5213     {
5214         /* TLSv1.2 server followed by resumption */
5215         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5216         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5217         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
5218         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
5219         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
5220         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5221         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5222         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
5223         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
5224         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5225         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
5226         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5227         {SSL_CB_EXIT, NULL}, {0, NULL},
5228     }, {
5229         /* TLSv1.2 client followed by resumption */
5230         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5231         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5232         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
5233         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
5234         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
5235         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
5236         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
5237         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5238         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5239         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
5240         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
5241         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
5242     }, {
5243         /* TLSv1.3 server followed by resumption */
5244         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5245         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5246         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
5247         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
5248         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
5249         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
5250         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
5251         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5252         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5253         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
5254         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
5255         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5256         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
5257     }, {
5258         /* TLSv1.3 client followed by resumption */
5259         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5260         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5261         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
5262         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
5263         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
5264         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
5265         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "},
5266         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
5267         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
5268         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
5269         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
5270         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5271         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5272         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
5273         {SSL_CB_EXIT, NULL}, {0, NULL},
5274     }, {
5275         /* TLSv1.3 server, early_data */
5276         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5277         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5278         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
5279         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5280         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
5281         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
5282         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
5283         {SSL_CB_EXIT, NULL}, {0, NULL},
5284     }, {
5285         /* TLSv1.3 client, early_data */
5286         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5287         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
5288         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5289         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
5290         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
5291         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
5292         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5293         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
5294         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
5295     }, {
5296         {0, NULL},
5297     }
5298 };
5299
5300 static void sslapi_info_callback(const SSL *s, int where, int ret)
5301 {
5302     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
5303
5304     /* We do not ever expect a connection to fail in this test */
5305     if (!TEST_false(ret == 0)) {
5306         info_cb_failed = 1;
5307         return;
5308     }
5309
5310     /*
5311      * Do some sanity checks. We never expect these things to happen in this
5312      * test
5313      */
5314     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
5315             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
5316             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
5317         info_cb_failed = 1;
5318         return;
5319     }
5320
5321     /* Now check we're in the right state */
5322     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
5323         info_cb_failed = 1;
5324         return;
5325     }
5326     if ((where & SSL_CB_LOOP) != 0
5327             && !TEST_int_eq(strcmp(SSL_state_string(s),
5328                             state[info_cb_this_state].statestr), 0)) {
5329         info_cb_failed = 1;
5330         return;
5331     }
5332
5333     /*
5334      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
5335      */
5336     if ((where & SSL_CB_HANDSHAKE_DONE)
5337             && SSL_in_init((SSL *)s) != 0) {
5338         info_cb_failed = 1;
5339         return;
5340     }
5341 }
5342
5343 /*
5344  * Test the info callback gets called when we expect it to.
5345  *
5346  * Test 0: TLSv1.2, server
5347  * Test 1: TLSv1.2, client
5348  * Test 2: TLSv1.3, server
5349  * Test 3: TLSv1.3, client
5350  * Test 4: TLSv1.3, server, early_data
5351  * Test 5: TLSv1.3, client, early_data
5352  */
5353 static int test_info_callback(int tst)
5354 {
5355     SSL_CTX *cctx = NULL, *sctx = NULL;
5356     SSL *clientssl = NULL, *serverssl = NULL;
5357     SSL_SESSION *clntsess = NULL;
5358     int testresult = 0;
5359     int tlsvers;
5360
5361     if (tst < 2) {
5362 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
5363 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
5364                                     || !defined(OPENSSL_NO_DH))
5365         tlsvers = TLS1_2_VERSION;
5366 #else
5367         return 1;
5368 #endif
5369     } else {
5370 #ifndef OPENSSL_NO_TLS1_3
5371         tlsvers = TLS1_3_VERSION;
5372 #else
5373         return 1;
5374 #endif
5375     }
5376
5377     /* Reset globals */
5378     info_cb_failed = 0;
5379     info_cb_this_state = -1;
5380     info_cb_offset = tst;
5381
5382 #ifndef OPENSSL_NO_TLS1_3
5383     if (tst >= 4) {
5384         SSL_SESSION *sess = NULL;
5385         size_t written, readbytes;
5386         unsigned char buf[80];
5387
5388         /* early_data tests */
5389         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
5390                                             &serverssl, &sess, 0)))
5391             goto end;
5392
5393         /* We don't actually need this reference */
5394         SSL_SESSION_free(sess);
5395
5396         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
5397                               sslapi_info_callback);
5398
5399         /* Write and read some early data and then complete the connection */
5400         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
5401                                             &written))
5402                 || !TEST_size_t_eq(written, strlen(MSG1))
5403                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
5404                                                     sizeof(buf), &readbytes),
5405                                 SSL_READ_EARLY_DATA_SUCCESS)
5406                 || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
5407                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
5408                                 SSL_EARLY_DATA_ACCEPTED)
5409                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
5410                                                     SSL_ERROR_NONE))
5411                 || !TEST_false(info_cb_failed))
5412             goto end;
5413
5414         testresult = 1;
5415         goto end;
5416     }
5417 #endif
5418
5419     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5420                                        TLS_client_method(),
5421                                        tlsvers, tlsvers, &sctx, &cctx, cert,
5422                                        privkey)))
5423         goto end;
5424
5425     /*
5426      * For even numbered tests we check the server callbacks. For odd numbers we
5427      * check the client.
5428      */
5429     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
5430                               sslapi_info_callback);
5431
5432     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5433                                           &clientssl, NULL, NULL))
5434         || !TEST_true(create_ssl_connection(serverssl, clientssl,
5435                                             SSL_ERROR_NONE))
5436         || !TEST_false(info_cb_failed))
5437     goto end;
5438
5439
5440
5441     clntsess = SSL_get1_session(clientssl);
5442     SSL_shutdown(clientssl);
5443     SSL_shutdown(serverssl);
5444     SSL_free(serverssl);
5445     SSL_free(clientssl);
5446     serverssl = clientssl = NULL;
5447
5448     /* Now do a resumption */
5449     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
5450                                       NULL))
5451             || !TEST_true(SSL_set_session(clientssl, clntsess))
5452             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5453                                                 SSL_ERROR_NONE))
5454             || !TEST_true(SSL_session_reused(clientssl))
5455             || !TEST_false(info_cb_failed))
5456         goto end;
5457
5458     testresult = 1;
5459
5460  end:
5461     SSL_free(serverssl);
5462     SSL_free(clientssl);
5463     SSL_SESSION_free(clntsess);
5464     SSL_CTX_free(sctx);
5465     SSL_CTX_free(cctx);
5466     return testresult;
5467 }
5468
5469 static int test_ssl_pending(int tst)
5470 {
5471     SSL_CTX *cctx = NULL, *sctx = NULL;
5472     SSL *clientssl = NULL, *serverssl = NULL;
5473     int testresult = 0;
5474     char msg[] = "A test message";
5475     char buf[5];
5476     size_t written, readbytes;
5477
5478     if (tst == 0) {
5479         if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5480                                            TLS_client_method(),
5481                                            TLS1_VERSION, TLS_MAX_VERSION,
5482                                            &sctx, &cctx, cert, privkey)))
5483             goto end;
5484     } else {
5485 #ifndef OPENSSL_NO_DTLS
5486         if (!TEST_true(create_ssl_ctx_pair(DTLS_server_method(),
5487                                            DTLS_client_method(),
5488                                            DTLS1_VERSION, DTLS_MAX_VERSION,
5489                                            &sctx, &cctx, cert, privkey)))
5490             goto end;
5491 #else
5492         return 1;
5493 #endif
5494     }
5495
5496     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5497                                              NULL, NULL))
5498             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5499                                                 SSL_ERROR_NONE)))
5500         goto end;
5501
5502     if (!TEST_int_eq(SSL_pending(clientssl), 0)
5503             || !TEST_false(SSL_has_pending(clientssl))
5504             || !TEST_int_eq(SSL_pending(serverssl), 0)
5505             || !TEST_false(SSL_has_pending(serverssl))
5506             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
5507             || !TEST_size_t_eq(written, sizeof(msg))
5508             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
5509             || !TEST_size_t_eq(readbytes, sizeof(buf))
5510             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
5511             || !TEST_true(SSL_has_pending(clientssl)))
5512         goto end;
5513
5514     testresult = 1;
5515
5516  end:
5517     SSL_free(serverssl);
5518     SSL_free(clientssl);
5519     SSL_CTX_free(sctx);
5520     SSL_CTX_free(cctx);
5521
5522     return testresult;
5523 }
5524
5525 static struct {
5526     unsigned int maxprot;
5527     const char *clntciphers;
5528     const char *clnttls13ciphers;
5529     const char *srvrciphers;
5530     const char *srvrtls13ciphers;
5531     const char *shared;
5532 } shared_ciphers_data[] = {
5533 /*
5534  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
5535  * TLSv1.3 is enabled but TLSv1.2 is disabled.
5536  */
5537 #if defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
5538     {
5539         TLS1_2_VERSION,
5540         "AES128-SHA:AES256-SHA",
5541         NULL,
5542         "AES256-SHA:DHE-RSA-AES128-SHA",
5543         NULL,
5544         "AES256-SHA"
5545     },
5546     {
5547         TLS1_2_VERSION,
5548         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
5549         NULL,
5550         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
5551         NULL,
5552         "AES128-SHA:AES256-SHA"
5553     },
5554     {
5555         TLS1_2_VERSION,
5556         "AES128-SHA:AES256-SHA",
5557         NULL,
5558         "AES128-SHA:DHE-RSA-AES128-SHA",
5559         NULL,
5560         "AES128-SHA"
5561     },
5562 #endif
5563 /*
5564  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
5565  * enabled.
5566  */
5567 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
5568     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
5569     {
5570         TLS1_3_VERSION,
5571         "AES128-SHA:AES256-SHA",
5572         NULL,
5573         "AES256-SHA:AES128-SHA256",
5574         NULL,
5575         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
5576         "TLS_AES_128_GCM_SHA256:AES256-SHA"
5577     },
5578 #endif
5579 #ifndef OPENSSL_NO_TLS1_3
5580     {
5581         TLS1_3_VERSION,
5582         "AES128-SHA",
5583         "TLS_AES_256_GCM_SHA384",
5584         "AES256-SHA",
5585         "TLS_AES_256_GCM_SHA384",
5586         "TLS_AES_256_GCM_SHA384"
5587     },
5588 #endif
5589 };
5590
5591 static int test_ssl_get_shared_ciphers(int tst)
5592 {
5593     SSL_CTX *cctx = NULL, *sctx = NULL;
5594     SSL *clientssl = NULL, *serverssl = NULL;
5595     int testresult = 0;
5596     char buf[1024];
5597
5598     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5599                                        TLS_client_method(),
5600                                        TLS1_VERSION,
5601                                        shared_ciphers_data[tst].maxprot,
5602                                        &sctx, &cctx, cert, privkey)))
5603         goto end;
5604
5605     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5606                                         shared_ciphers_data[tst].clntciphers))
5607             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
5608                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
5609                                     shared_ciphers_data[tst].clnttls13ciphers)))
5610             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
5611                                         shared_ciphers_data[tst].srvrciphers))
5612             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
5613                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
5614                                     shared_ciphers_data[tst].srvrtls13ciphers))))
5615         goto end;
5616
5617
5618     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5619                                              NULL, NULL))
5620             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5621                                                 SSL_ERROR_NONE)))
5622         goto end;
5623
5624     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
5625             || !TEST_int_eq(strcmp(buf, shared_ciphers_data[tst].shared), 0)) {
5626         TEST_info("Shared ciphers are: %s\n", buf);
5627         goto end;
5628     }
5629
5630     testresult = 1;
5631
5632  end:
5633     SSL_free(serverssl);
5634     SSL_free(clientssl);
5635     SSL_CTX_free(sctx);
5636     SSL_CTX_free(cctx);
5637
5638     return testresult;
5639 }
5640
5641 static const char *appdata = "Hello World";
5642 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
5643 static int tick_key_renew = 0;
5644 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
5645
5646 static int gen_tick_cb(SSL *s, void *arg)
5647 {
5648     gen_tick_called = 1;
5649
5650     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
5651                                            strlen(appdata));
5652 }
5653
5654 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
5655                                      const unsigned char *keyname,
5656                                      size_t keyname_length,
5657                                      SSL_TICKET_STATUS status,
5658                                      void *arg)
5659 {
5660     void *tickdata;
5661     size_t tickdlen;
5662
5663     dec_tick_called = 1;
5664
5665     if (status == SSL_TICKET_EMPTY)
5666         return SSL_TICKET_RETURN_IGNORE_RENEW;
5667
5668     if (!TEST_true(status == SSL_TICKET_SUCCESS
5669                    || status == SSL_TICKET_SUCCESS_RENEW))
5670         return SSL_TICKET_RETURN_ABORT;
5671
5672     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
5673                                                    &tickdlen))
5674             || !TEST_size_t_eq(tickdlen, strlen(appdata))
5675             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
5676         return SSL_TICKET_RETURN_ABORT;
5677
5678     if (tick_key_cb_called)  {
5679         /* Don't change what the ticket key callback wanted to do */
5680         switch (status) {
5681         case SSL_TICKET_NO_DECRYPT:
5682             return SSL_TICKET_RETURN_IGNORE_RENEW;
5683
5684         case SSL_TICKET_SUCCESS:
5685             return SSL_TICKET_RETURN_USE;
5686
5687         case SSL_TICKET_SUCCESS_RENEW:
5688             return SSL_TICKET_RETURN_USE_RENEW;
5689
5690         default:
5691             return SSL_TICKET_RETURN_ABORT;
5692         }
5693     }
5694     return tick_dec_ret;
5695
5696 }
5697
5698 static int tick_key_cb(SSL *s, unsigned char key_name[16],
5699                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
5700                        HMAC_CTX *hctx, int enc)
5701 {
5702     const unsigned char tick_aes_key[16] = "0123456789abcdef";
5703     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
5704
5705     tick_key_cb_called = 1;
5706     memset(iv, 0, AES_BLOCK_SIZE);
5707     memset(key_name, 0, 16);
5708     if (!EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, tick_aes_key, iv, enc)
5709             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key),
5710                              EVP_sha256(), NULL))
5711         return -1;
5712
5713     return tick_key_renew ? 2 : 1;
5714 }
5715
5716 /*
5717  * Test the various ticket callbacks
5718  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
5719  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
5720  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
5721  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
5722  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
5723  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
5724  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
5725  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
5726  * Test 8: TLSv1.2, ticket key callback, ticket, no renewal
5727  * Test 9: TLSv1.3, ticket key callback, ticket, no renewal
5728  * Test 10: TLSv1.2, ticket key callback, ticket, renewal
5729  * Test 11: TLSv1.3, ticket key callback, ticket, renewal
5730  */
5731 static int test_ticket_callbacks(int tst)
5732 {
5733     SSL_CTX *cctx = NULL, *sctx = NULL;
5734     SSL *clientssl = NULL, *serverssl = NULL;
5735     SSL_SESSION *clntsess = NULL;
5736     int testresult = 0;
5737
5738 #ifdef OPENSSL_NO_TLS1_2
5739     if (tst % 2 == 0)
5740         return 1;
5741 #endif
5742 #ifdef OPENSSL_NO_TLS1_3
5743     if (tst % 2 == 1)
5744         return 1;
5745 #endif
5746
5747     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
5748
5749     /* Which tests the ticket key callback should request renewal for */
5750     if (tst == 10 || tst == 11)
5751         tick_key_renew = 1;
5752     else
5753         tick_key_renew = 0;
5754
5755     /* Which tests the decrypt ticket callback should request renewal for */
5756     switch (tst) {
5757     case 0:
5758     case 1:
5759         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
5760         break;
5761
5762     case 2:
5763     case 3:
5764         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
5765         break;
5766
5767     case 4:
5768     case 5:
5769         tick_dec_ret = SSL_TICKET_RETURN_USE;
5770         break;
5771
5772     case 6:
5773     case 7:
5774         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
5775         break;
5776
5777     default:
5778         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
5779     }
5780
5781     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5782                                        TLS_client_method(),
5783                                        TLS1_VERSION,
5784                                        ((tst % 2) == 0) ? TLS1_2_VERSION
5785                                                         : TLS1_3_VERSION,
5786                                        &sctx, &cctx, cert, privkey)))
5787         goto end;
5788
5789     /*
5790      * We only want sessions to resume from tickets - not the session cache. So
5791      * switch the cache off.
5792      */
5793     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
5794         goto end;
5795
5796     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
5797                                                  NULL)))
5798         goto end;
5799
5800     if (tst >= 8
5801             && !TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
5802         goto end;
5803
5804     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5805                                              NULL, NULL))
5806             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5807                                                 SSL_ERROR_NONE)))
5808         goto end;
5809
5810     /*
5811      * The decrypt ticket key callback in TLSv1.2 should be called even though
5812      * we have no ticket yet, because it gets called with a status of
5813      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
5814      * actually send any ticket data). This does not happen in TLSv1.3 because
5815      * it is not valid to send empty ticket data in TLSv1.3.
5816      */
5817     if (!TEST_int_eq(gen_tick_called, 1)
5818             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
5819         goto end;
5820
5821     gen_tick_called = dec_tick_called = 0;
5822
5823     clntsess = SSL_get1_session(clientssl);
5824     SSL_shutdown(clientssl);
5825     SSL_shutdown(serverssl);
5826     SSL_free(serverssl);
5827     SSL_free(clientssl);
5828     serverssl = clientssl = NULL;
5829
5830     /* Now do a resumption */
5831     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
5832                                       NULL))
5833             || !TEST_true(SSL_set_session(clientssl, clntsess))
5834             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5835                                                 SSL_ERROR_NONE)))
5836         goto end;
5837
5838     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
5839             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW) {
5840         if (!TEST_false(SSL_session_reused(clientssl)))
5841             goto end;
5842     } else {
5843         if (!TEST_true(SSL_session_reused(clientssl)))
5844             goto end;
5845     }
5846
5847     if (!TEST_int_eq(gen_tick_called,
5848                      (tick_key_renew
5849                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
5850                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
5851                      ? 1 : 0)
5852             || !TEST_int_eq(dec_tick_called, 1))
5853         goto end;
5854
5855     testresult = 1;
5856
5857  end:
5858     SSL_SESSION_free(clntsess);
5859     SSL_free(serverssl);
5860     SSL_free(clientssl);
5861     SSL_CTX_free(sctx);
5862     SSL_CTX_free(cctx);
5863
5864     return testresult;
5865 }
5866
5867 /*
5868  * Test bi-directional shutdown.
5869  * Test 0: TLSv1.2
5870  * Test 1: TLSv1.2, server continues to read/write after client shutdown
5871  * Test 2: TLSv1.3, no pending NewSessionTicket messages
5872  * Test 3: TLSv1.3, pending NewSessionTicket messages
5873  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
5874  *                  sends key update, client reads it
5875  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
5876  *                  sends CertificateRequest, client reads and ignores it
5877  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
5878  *                  doesn't read it
5879  */
5880 static int test_shutdown(int tst)
5881 {
5882     SSL_CTX *cctx = NULL, *sctx = NULL;
5883     SSL *clientssl = NULL, *serverssl = NULL;
5884     int testresult = 0;
5885     char msg[] = "A test message";
5886     char buf[80];
5887     size_t written, readbytes;
5888     SSL_SESSION *sess;
5889
5890 #ifdef OPENSSL_NO_TLS1_2
5891     if (tst <= 1)
5892         return 1;
5893 #endif
5894 #ifdef OPENSSL_NO_TLS1_3
5895     if (tst >= 2)
5896         return 1;
5897 #endif
5898
5899     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5900                                        TLS_client_method(),
5901                                        TLS1_VERSION,
5902                                        (tst <= 1) ? TLS1_2_VERSION
5903                                                   : TLS1_3_VERSION,
5904                                        &sctx, &cctx, cert, privkey)))
5905         goto end;
5906
5907     if (tst == 5)
5908         SSL_CTX_set_post_handshake_auth(cctx, 1);
5909
5910     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5911                                              NULL, NULL)))
5912         goto end;
5913
5914     if (tst == 3) {
5915         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
5916                                                   SSL_ERROR_NONE, 1))
5917                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
5918                 || !TEST_false(SSL_SESSION_is_resumable(sess)))
5919             goto end;
5920     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5921                                               SSL_ERROR_NONE))
5922             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
5923             || !TEST_true(SSL_SESSION_is_resumable(sess))) {
5924         goto end;
5925     }
5926
5927     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
5928         goto end;
5929
5930     if (tst >= 4) {
5931         /*
5932          * Reading on the server after the client has sent close_notify should
5933          * fail and provide SSL_ERROR_ZERO_RETURN
5934          */
5935         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
5936                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
5937                                 SSL_ERROR_ZERO_RETURN)
5938                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
5939                                 SSL_RECEIVED_SHUTDOWN)
5940                    /*
5941                     * Even though we're shutdown on receive we should still be
5942                     * able to write.
5943                     */
5944                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
5945             goto end;
5946         if (tst == 4
5947                 && !TEST_true(SSL_key_update(serverssl,
5948                                              SSL_KEY_UPDATE_REQUESTED)))
5949             goto end;
5950         if (tst == 5) {
5951             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
5952             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
5953                 goto end;
5954         }
5955         if ((tst == 4 || tst == 5)
5956                 && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
5957             goto end;
5958         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
5959             goto end;
5960         if (tst == 4 || tst == 5) {
5961             /* Should still be able to read data from server */
5962             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
5963                                        &readbytes))
5964                     || !TEST_size_t_eq(readbytes, sizeof(msg))
5965                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
5966                     || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
5967                                               &readbytes))
5968                     || !TEST_size_t_eq(readbytes, sizeof(msg))
5969                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
5970                 goto end;
5971         }
5972     }
5973
5974     /* Writing on the client after sending close_notify shouldn't be possible */
5975     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
5976         goto end;
5977
5978     if (tst < 4) {
5979         /*
5980          * For these tests the client has sent close_notify but it has not yet
5981          * been received by the server. The server has not sent close_notify
5982          * yet.
5983          */
5984         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
5985                    /*
5986                     * Writing on the server after sending close_notify shouldn't
5987                     * be possible.
5988                     */
5989                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
5990                 || !TEST_int_eq(SSL_shutdown(clientssl), 1)
5991                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
5992                 || !TEST_true(SSL_SESSION_is_resumable(sess))
5993                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
5994             goto end;
5995     } else if (tst == 4 || tst == 5) {
5996         /*
5997          * In this test the client has sent close_notify and it has been
5998          * received by the server which has responded with a close_notify. The
5999          * client needs to read the close_notify sent by the server.
6000          */
6001         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
6002                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6003                 || !TEST_true(SSL_SESSION_is_resumable(sess)))
6004             goto end;
6005     } else {
6006         /*
6007          * tst == 6
6008          *
6009          * The client has sent close_notify and is expecting a close_notify
6010          * back, but instead there is application data first. The shutdown
6011          * should fail with a fatal error.
6012          */
6013         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
6014                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
6015             goto end;
6016     }
6017
6018     testresult = 1;
6019
6020  end:
6021     SSL_free(serverssl);
6022     SSL_free(clientssl);
6023     SSL_CTX_free(sctx);
6024     SSL_CTX_free(cctx);
6025
6026     return testresult;
6027 }
6028
6029 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OPENSSL_NO_TLS1_3)
6030 static int cert_cb_cnt;
6031
6032 static int cert_cb(SSL *s, void *arg)
6033 {
6034     SSL_CTX *ctx = (SSL_CTX *)arg;
6035     BIO *in = NULL;
6036     EVP_PKEY *pkey = NULL;
6037     X509 *x509 = NULL, *rootx = NULL;
6038     STACK_OF(X509) *chain = NULL;
6039     char *rootfile = NULL, *ecdsacert = NULL, *ecdsakey = NULL;
6040     int ret = 0;
6041
6042     if (cert_cb_cnt == 0) {
6043         /* Suspend the handshake */
6044         cert_cb_cnt++;
6045         return -1;
6046     } else if (cert_cb_cnt == 1) {
6047         /*
6048          * Update the SSL_CTX, set the certificate and private key and then
6049          * continue the handshake normally.
6050          */
6051         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
6052             return 0;
6053
6054         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
6055                 || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
6056                                                       SSL_FILETYPE_PEM))
6057                 || !TEST_true(SSL_check_private_key(s)))
6058             return 0;
6059         cert_cb_cnt++;
6060         return 1;
6061     } else if (cert_cb_cnt == 3) {
6062         int rv;
6063
6064         rootfile = test_mk_file_path(certsdir, "rootcert.pem");
6065         ecdsacert = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
6066         ecdsakey = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
6067         if (!TEST_ptr(rootfile) || !TEST_ptr(ecdsacert) || !TEST_ptr(ecdsakey))
6068             goto out;
6069         chain = sk_X509_new_null();
6070         if (!TEST_ptr(chain))
6071             goto out;
6072         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6073                 || !TEST_int_ge(BIO_read_filename(in, rootfile), 0)
6074                 || !TEST_ptr(rootx = PEM_read_bio_X509(in, NULL, NULL, NULL))
6075                 || !TEST_true(sk_X509_push(chain, rootx)))
6076             goto out;
6077         rootx = NULL;
6078         BIO_free(in);
6079         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6080                 || !TEST_int_ge(BIO_read_filename(in, ecdsacert), 0)
6081                 || !TEST_ptr(x509 = PEM_read_bio_X509(in, NULL, NULL, NULL)))
6082             goto out;
6083         BIO_free(in);
6084         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6085                 || !TEST_int_ge(BIO_read_filename(in, ecdsakey), 0)
6086                 || !TEST_ptr(pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL)))
6087             goto out;
6088         rv = SSL_check_chain(s, x509, pkey, chain);
6089         /*
6090          * If the cert doesn't show as valid here (e.g., because we don't
6091          * have any shared sigalgs), then we will not set it, and there will
6092          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
6093          * will cause tls_choose_sigalgs() to fail the connection.
6094          */
6095         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
6096                 == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
6097             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
6098                 goto out;
6099         }
6100
6101         ret = 1;
6102     }
6103
6104     /* Abort the handshake */
6105  out:
6106     OPENSSL_free(ecdsacert);
6107     OPENSSL_free(ecdsakey);
6108     OPENSSL_free(rootfile);
6109     BIO_free(in);
6110     EVP_PKEY_free(pkey);
6111     X509_free(x509);
6112     X509_free(rootx);
6113     sk_X509_pop_free(chain, X509_free);
6114     return ret;
6115 }
6116
6117 /*
6118  * Test the certificate callback.
6119  * Test 0: Callback fails
6120  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
6121  * Test 2: Success - SSL_set_SSL_CTX() in the callback
6122  * Test 3: Success - Call SSL_check_chain from the callback
6123  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
6124  *                   chain
6125  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
6126  */
6127 static int test_cert_cb_int(int prot, int tst)
6128 {
6129     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
6130     SSL *clientssl = NULL, *serverssl = NULL;
6131     int testresult = 0, ret;
6132
6133 #ifdef OPENSSL_NO_EC
6134     /* We use an EC cert in these tests, so we skip in a no-ec build */
6135     if (tst >= 3)
6136         return 1;
6137 #endif
6138
6139     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6140                                        TLS_client_method(),
6141                                        TLS1_VERSION,
6142                                        prot,
6143                                        &sctx, &cctx, NULL, NULL)))
6144         goto end;
6145
6146     if (tst == 0)
6147         cert_cb_cnt = -1;
6148     else if (tst >= 3)
6149         cert_cb_cnt = 3;
6150     else
6151         cert_cb_cnt = 0;
6152
6153     if (tst == 2)
6154         snictx = SSL_CTX_new(TLS_server_method());
6155     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
6156
6157     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6158                                       NULL, NULL)))
6159         goto end;
6160
6161     if (tst == 4) {
6162         /*
6163          * We cause SSL_check_chain() to fail by specifying sig_algs that
6164          * the chain doesn't meet (the root uses an RSA cert)
6165          */
6166         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
6167                                              "ecdsa_secp256r1_sha256")))
6168             goto end;
6169     } else if (tst == 5) {
6170         /*
6171          * We cause SSL_check_chain() to fail by specifying sig_algs that
6172          * the ee cert doesn't meet (the ee uses an ECDSA cert)
6173          */
6174         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
6175                            "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
6176             goto end;
6177     }
6178
6179     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
6180     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
6181             || (tst > 0
6182                 && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
6183         goto end;
6184     }
6185
6186     testresult = 1;
6187
6188  end:
6189     SSL_free(serverssl);
6190     SSL_free(clientssl);
6191     SSL_CTX_free(sctx);
6192     SSL_CTX_free(cctx);
6193     SSL_CTX_free(snictx);
6194
6195     return testresult;
6196 }
6197 #endif
6198
6199 static int test_cert_cb(int tst)
6200 {
6201     int testresult = 1;
6202
6203 #ifndef OPENSSL_NO_TLS1_2
6204     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
6205 #endif
6206 #ifndef OPENSSL_NO_TLS1_3
6207     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
6208 #endif
6209
6210     return testresult;
6211 }
6212
6213 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
6214 {
6215     X509 *xcert, *peer;
6216     EVP_PKEY *privpkey;
6217     BIO *in = NULL;
6218
6219     /* Check that SSL_get_peer_certificate() returns something sensible */
6220     peer = SSL_get_peer_certificate(ssl);
6221     if (!TEST_ptr(peer))
6222         return 0;
6223     X509_free(peer);
6224
6225     in = BIO_new_file(cert, "r");
6226     if (!TEST_ptr(in))
6227         return 0;
6228
6229     xcert = PEM_read_bio_X509(in, NULL, NULL, NULL);
6230     BIO_free(in);
6231     if (!TEST_ptr(xcert))
6232         return 0;
6233
6234     in = BIO_new_file(privkey, "r");
6235     if (!TEST_ptr(in)) {
6236         X509_free(xcert);
6237         return 0;
6238     }
6239
6240     privpkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
6241     BIO_free(in);
6242     if (!TEST_ptr(privpkey)) {
6243         X509_free(xcert);
6244         return 0;
6245     }
6246
6247     *x509 = xcert;
6248     *pkey = privpkey;
6249
6250     return 1;
6251 }
6252
6253 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
6254 {
6255     return 1;
6256 }
6257
6258 static int test_client_cert_cb(int tst)
6259 {
6260     SSL_CTX *cctx = NULL, *sctx = NULL;
6261     SSL *clientssl = NULL, *serverssl = NULL;
6262     int testresult = 0;
6263
6264 #ifdef OPENSSL_NO_TLS1_2
6265     if (tst == 0)
6266         return 1;
6267 #endif
6268 #ifdef OPENSSL_NO_TLS1_3
6269     if (tst == 1)
6270         return 1;
6271 #endif
6272
6273     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6274                                        TLS_client_method(),
6275                                        TLS1_VERSION,
6276                                        tst == 0 ? TLS1_2_VERSION
6277                                                 : TLS1_3_VERSION,
6278                                        &sctx, &cctx, cert, privkey)))
6279         goto end;
6280
6281     /*
6282      * Test that setting a client_cert_cb results in a client certificate being
6283      * sent.
6284      */
6285     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
6286     SSL_CTX_set_verify(sctx,
6287                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
6288                        verify_cb);
6289
6290     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6291                                       NULL, NULL))
6292             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6293                                                 SSL_ERROR_NONE)))
6294         goto end;
6295
6296     testresult = 1;
6297
6298  end:
6299     SSL_free(serverssl);
6300     SSL_free(clientssl);
6301     SSL_CTX_free(sctx);
6302     SSL_CTX_free(cctx);
6303
6304     return testresult;
6305 }
6306
6307 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OPENSSL_NO_TLS1_3)
6308 /*
6309  * Test setting certificate authorities on both client and server.
6310  *
6311  * Test 0: SSL_CTX_set0_CA_list() only
6312  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
6313  * Test 2: Only SSL_CTX_set_client_CA_list()
6314  */
6315 static int test_ca_names_int(int prot, int tst)
6316 {
6317     SSL_CTX *cctx = NULL, *sctx = NULL;
6318     SSL *clientssl = NULL, *serverssl = NULL;
6319     int testresult = 0;
6320     size_t i;
6321     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
6322     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
6323     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
6324     const STACK_OF(X509_NAME) *sktmp = NULL;
6325
6326     for (i = 0; i < OSSL_NELEM(name); i++) {
6327         name[i] = X509_NAME_new();
6328         if (!TEST_ptr(name[i])
6329                 || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
6330                                                          MBSTRING_ASC,
6331                                                          (unsigned char *)
6332                                                          strnames[i],
6333                                                          -1, -1, 0)))
6334             goto end;
6335     }
6336
6337     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6338                                        TLS_client_method(),
6339                                        TLS1_VERSION,
6340                                        prot,
6341                                        &sctx, &cctx, cert, privkey)))
6342         goto end;
6343
6344     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
6345
6346     if (tst == 0 || tst == 1) {
6347         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
6348                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
6349                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
6350                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
6351                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
6352                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
6353             goto end;
6354
6355         SSL_CTX_set0_CA_list(sctx, sk1);
6356         SSL_CTX_set0_CA_list(cctx, sk2);
6357         sk1 = sk2 = NULL;
6358     }
6359     if (tst == 1 || tst == 2) {
6360         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
6361                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
6362                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
6363                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
6364                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
6365                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
6366             goto end;
6367
6368         SSL_CTX_set_client_CA_list(sctx, sk1);
6369         SSL_CTX_set_client_CA_list(cctx, sk2);
6370         sk1 = sk2 = NULL;
6371     }
6372
6373     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6374                                       NULL, NULL))
6375             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6376                                                 SSL_ERROR_NONE)))
6377         goto end;
6378
6379     /*
6380      * We only expect certificate authorities to have been sent to the server
6381      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
6382      */
6383     sktmp = SSL_get0_peer_CA_list(serverssl);
6384     if (prot == TLS1_3_VERSION
6385             && (tst == 0 || tst == 1)) {
6386         if (!TEST_ptr(sktmp)
6387                 || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
6388                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
6389                                               name[0]), 0)
6390                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
6391                                               name[1]), 0))
6392             goto end;
6393     } else if (!TEST_ptr_null(sktmp)) {
6394         goto end;
6395     }
6396
6397     /*
6398      * In all tests we expect certificate authorities to have been sent to the
6399      * client. However, SSL_set_client_CA_list() should override
6400      * SSL_set0_CA_list()
6401      */
6402     sktmp = SSL_get0_peer_CA_list(clientssl);
6403     if (!TEST_ptr(sktmp)
6404             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
6405             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
6406                                           name[tst == 0 ? 0 : 2]), 0)
6407             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
6408                                           name[tst == 0 ? 1 : 3]), 0))
6409         goto end;
6410
6411     testresult = 1;
6412
6413  end:
6414     SSL_free(serverssl);
6415     SSL_free(clientssl);
6416     SSL_CTX_free(sctx);
6417     SSL_CTX_free(cctx);
6418     for (i = 0; i < OSSL_NELEM(name); i++)
6419         X509_NAME_free(name[i]);
6420     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
6421     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
6422
6423     return testresult;
6424 }
6425 #endif
6426
6427 static int test_ca_names(int tst)
6428 {
6429     int testresult = 1;
6430
6431 #ifndef OPENSSL_NO_TLS1_2
6432     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
6433 #endif
6434 #ifndef OPENSSL_NO_TLS1_3
6435     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
6436 #endif
6437
6438     return testresult;
6439 }
6440
6441 /*
6442  * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
6443  * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
6444  * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
6445  * Test 3: Client does not set servername on initial handshake (TLSv1.2)
6446  * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
6447  * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
6448  * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
6449  * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
6450  * Test 8: Client does not set servername on initial handshake(TLSv1.3)
6451  * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
6452  */
6453 static int test_servername(int tst)
6454 {
6455     SSL_CTX *cctx = NULL, *sctx = NULL;
6456     SSL *clientssl = NULL, *serverssl = NULL;
6457     int testresult = 0;
6458     SSL_SESSION *sess = NULL;
6459     const char *sexpectedhost = NULL, *cexpectedhost = NULL;
6460
6461 #ifdef OPENSSL_NO_TLS1_2
6462     if (tst <= 4)
6463         return 1;
6464 #endif
6465 #ifdef OPENSSL_NO_TLS1_3
6466     if (tst >= 5)
6467         return 1;
6468 #endif
6469
6470     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6471                                        TLS_client_method(),
6472                                        TLS1_VERSION,
6473                                        (tst <= 4) ? TLS1_2_VERSION
6474                                                   : TLS1_3_VERSION,
6475                                        &sctx, &cctx, cert, privkey))
6476             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6477                                              NULL, NULL)))
6478         goto end;
6479
6480     if (tst != 1 && tst != 6) {
6481         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
6482                                                               hostname_cb)))
6483             goto end;
6484     }
6485
6486     if (tst != 3 && tst != 8) {
6487         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
6488             goto end;
6489         sexpectedhost = cexpectedhost = "goodhost";
6490     }
6491
6492     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
6493         goto end;
6494
6495     if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
6496                      cexpectedhost)
6497             || !TEST_str_eq(SSL_get_servername(serverssl,
6498                                                TLSEXT_NAMETYPE_host_name),
6499                             sexpectedhost))
6500         goto end;
6501
6502     /* Now repeat with a resumption handshake */
6503
6504     if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
6505             || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
6506             || !TEST_true(SSL_SESSION_is_resumable(sess))
6507             || !TEST_int_eq(SSL_shutdown(serverssl), 0))
6508         goto end;
6509
6510     SSL_free(clientssl);
6511     SSL_free(serverssl);
6512     clientssl = serverssl = NULL;
6513
6514     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6515                                       NULL)))
6516         goto end;
6517
6518     if (!TEST_true(SSL_set_session(clientssl, sess)))
6519         goto end;
6520
6521     sexpectedhost = cexpectedhost = "goodhost";
6522     if (tst == 2 || tst == 7) {
6523         /* Set an inconsistent hostname */
6524         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
6525             goto end;
6526         /*
6527          * In TLSv1.2 we expect the hostname from the original handshake, in
6528          * TLSv1.3 we expect the hostname from this handshake
6529          */
6530         if (tst == 7)
6531             sexpectedhost = cexpectedhost = "altgoodhost";
6532
6533         if (!TEST_str_eq(SSL_get_servername(clientssl,
6534                                             TLSEXT_NAMETYPE_host_name),
6535                          "altgoodhost"))
6536             goto end;
6537     } else if (tst == 4 || tst == 9) {
6538         /*
6539          * A TLSv1.3 session does not associate a session with a servername,
6540          * but a TLSv1.2 session does.
6541          */
6542         if (tst == 9)
6543             sexpectedhost = cexpectedhost = NULL;
6544
6545         if (!TEST_str_eq(SSL_get_servername(clientssl,
6546                                             TLSEXT_NAMETYPE_host_name),
6547                          cexpectedhost))
6548             goto end;
6549     } else {
6550         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
6551             goto end;
6552         /*
6553          * In a TLSv1.2 resumption where the hostname was not acknowledged
6554          * we expect the hostname on the server to be empty. On the client we
6555          * return what was requested in this case.
6556          *
6557          * Similarly if the client didn't set a hostname on an original TLSv1.2
6558          * session but is now, the server hostname will be empty, but the client
6559          * is as we set it.
6560          */
6561         if (tst == 1 || tst == 3)
6562             sexpectedhost = NULL;
6563
6564         if (!TEST_str_eq(SSL_get_servername(clientssl,
6565                                             TLSEXT_NAMETYPE_host_name),
6566                          "goodhost"))
6567             goto end;
6568     }
6569
6570     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
6571         goto end;
6572
6573     if (!TEST_true(SSL_session_reused(clientssl))
6574             || !TEST_true(SSL_session_reused(serverssl))
6575             || !TEST_str_eq(SSL_get_servername(clientssl,
6576                                                TLSEXT_NAMETYPE_host_name),
6577                             cexpectedhost)
6578             || !TEST_str_eq(SSL_get_servername(serverssl,
6579                                                TLSEXT_NAMETYPE_host_name),
6580                             sexpectedhost))
6581         goto end;
6582
6583     testresult = 1;
6584
6585  end:
6586     SSL_SESSION_free(sess);
6587     SSL_free(serverssl);
6588     SSL_free(clientssl);
6589     SSL_CTX_free(sctx);
6590     SSL_CTX_free(cctx);
6591
6592     return testresult;
6593 }
6594
6595 #ifndef OPENSSL_NO_TLS1_2
6596 static int test_ssl_dup(void)
6597 {
6598     SSL_CTX *cctx = NULL, *sctx = NULL;
6599     SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL;
6600     int testresult = 0;
6601     BIO *rbio = NULL, *wbio = NULL;
6602
6603     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6604                                        TLS_client_method(),
6605                                        0,
6606                                        0,
6607                                        &sctx, &cctx, cert, privkey)))
6608         goto end;
6609
6610     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6611                                              NULL, NULL)))
6612         goto end;
6613
6614     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
6615             || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION)))
6616         goto end;
6617
6618     client2ssl = SSL_dup(clientssl);
6619     rbio = SSL_get_rbio(clientssl);
6620     if (!TEST_ptr(rbio)
6621             || !TEST_true(BIO_up_ref(rbio)))
6622         goto end;
6623     SSL_set0_rbio(client2ssl, rbio);
6624     rbio = NULL;
6625
6626     wbio = SSL_get_wbio(clientssl);
6627     if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio)))
6628         goto end;
6629     SSL_set0_wbio(client2ssl, wbio);
6630     rbio = NULL;
6631
6632     if (!TEST_ptr(client2ssl)
6633                /* Handshake not started so pointers should be different */
6634             || !TEST_ptr_ne(clientssl, client2ssl))
6635         goto end;
6636
6637     if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION)
6638             || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION))
6639         goto end;
6640
6641     if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE)))
6642         goto end;
6643
6644     SSL_free(clientssl);
6645     clientssl = SSL_dup(client2ssl);
6646     if (!TEST_ptr(clientssl)
6647                /* Handshake has finished so pointers should be the same */
6648             || !TEST_ptr_eq(clientssl, client2ssl))
6649         goto end;
6650
6651     testresult = 1;
6652
6653  end:
6654     SSL_free(serverssl);
6655     SSL_free(clientssl);
6656     SSL_free(client2ssl);
6657     SSL_CTX_free(sctx);
6658     SSL_CTX_free(cctx);
6659
6660     return testresult;
6661 }
6662 #endif
6663
6664 #ifndef OPENSSL_NO_TLS1_3
6665 /*
6666  * Test that setting an SNI callback works with TLSv1.3. Specifically we check
6667  * that it works even without a certificate configured for the original
6668  * SSL_CTX
6669  */
6670 static int test_sni_tls13(void)
6671 {
6672     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6673     SSL *clientssl = NULL, *serverssl = NULL;
6674     int testresult = 0;
6675
6676     /* Reset callback counter */
6677     snicb = 0;
6678
6679     /* Create an initial SSL_CTX with no certificate configured */
6680     sctx = SSL_CTX_new(TLS_server_method());
6681     if (!TEST_ptr(sctx))
6682         goto end;
6683     /* Require TLSv1.3 as a minimum */
6684     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
6685                                        TLS1_3_VERSION, 0, &sctx2, &cctx, cert,
6686                                        privkey)))
6687         goto end;
6688
6689     /* Set up SNI */
6690     if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
6691             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
6692         goto end;
6693
6694     /*
6695      * Connection should still succeed because the final SSL_CTX has the right
6696      * certificates configured.
6697      */
6698     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6699                                       &clientssl, NULL, NULL))
6700             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6701                                                 SSL_ERROR_NONE)))
6702         goto end;
6703
6704     /* We should have had the SNI callback called exactly once */
6705     if (!TEST_int_eq(snicb, 1))
6706         goto end;
6707
6708     testresult = 1;
6709
6710 end:
6711     SSL_free(serverssl);
6712     SSL_free(clientssl);
6713     SSL_CTX_free(sctx2);
6714     SSL_CTX_free(sctx);
6715     SSL_CTX_free(cctx);
6716     return testresult;
6717 }
6718 #endif
6719 /*
6720  * Test that setting an ALPN does not violate RFC
6721  */
6722 static int test_set_alpn(void)
6723 {
6724     SSL_CTX *ctx = NULL;
6725     SSL *ssl = NULL;
6726     int testresult = 0;
6727
6728     unsigned char bad0[] = { 0x00, 'b', 'a', 'd' };
6729     unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' };
6730     unsigned char bad1[] = { 0x01, 'b', 'a', 'd' };
6731     unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00};
6732     unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd'};
6733     unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd'};
6734
6735     /* Create an initial SSL_CTX with no certificate configured */
6736     ctx = SSL_CTX_new(TLS_server_method());
6737     if (!TEST_ptr(ctx))
6738         goto end;
6739
6740     /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */
6741     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2)))
6742         goto end;
6743     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0)))
6744         goto end;
6745     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good))))
6746         goto end;
6747     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1)))
6748         goto end;
6749     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0))))
6750         goto end;
6751     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1))))
6752         goto end;
6753     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2))))
6754         goto end;
6755     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3))))
6756         goto end;
6757     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4))))
6758         goto end;
6759
6760     ssl = SSL_new(ctx);
6761     if (!TEST_ptr(ssl))
6762         goto end;
6763
6764     if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2)))
6765         goto end;
6766     if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0)))
6767         goto end;
6768     if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good))))
6769         goto end;
6770     if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1)))
6771         goto end;
6772     if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0))))
6773         goto end;
6774     if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1))))
6775         goto end;
6776     if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2))))
6777         goto end;
6778     if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3))))
6779         goto end;
6780     if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4))))
6781         goto end;
6782
6783     testresult = 1;
6784
6785 end:
6786     SSL_free(ssl);
6787     SSL_CTX_free(ctx);
6788     return testresult;
6789 }
6790
6791 static int test_inherit_verify_param(void)
6792 {
6793     int testresult = 0;
6794
6795     SSL_CTX *ctx = NULL;
6796     X509_VERIFY_PARAM *cp = NULL;
6797     SSL *ssl = NULL;
6798     X509_VERIFY_PARAM *sp = NULL;
6799     int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
6800
6801     ctx = SSL_CTX_new(TLS_server_method());
6802     if (!TEST_ptr(ctx))
6803         goto end;
6804
6805     cp = SSL_CTX_get0_param(ctx);
6806     if (!TEST_ptr(cp))
6807         goto end;
6808     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0))
6809         goto end;
6810
6811     X509_VERIFY_PARAM_set_hostflags(cp, hostflags);
6812
6813     ssl = SSL_new(ctx);
6814     if (!TEST_ptr(ssl))
6815         goto end;
6816
6817     sp = SSL_get0_param(ssl);
6818     if (!TEST_ptr(sp))
6819         goto end;
6820     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags))
6821         goto end;
6822
6823     testresult = 1;
6824
6825  end:
6826     SSL_free(ssl);
6827     SSL_CTX_free(ctx);
6828
6829     return testresult;
6830 }
6831
6832 int setup_tests(void)
6833 {
6834     if (!TEST_ptr(certsdir = test_get_argument(0))
6835             || !TEST_ptr(srpvfile = test_get_argument(1))
6836             || !TEST_ptr(tmpfilename = test_get_argument(2)))
6837         return 0;
6838
6839     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
6840 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
6841         TEST_error("not supported in this build");
6842         return 0;
6843 #else
6844         int i, mcount, rcount, fcount;
6845
6846         for (i = 0; i < 4; i++)
6847             test_export_key_mat(i);
6848         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
6849         test_printf_stdout("malloc %d realloc %d free %d\n",
6850                 mcount, rcount, fcount);
6851         return 1;
6852 #endif
6853     }
6854
6855     cert = test_mk_file_path(certsdir, "servercert.pem");
6856     if (cert == NULL)
6857         return 0;
6858
6859     privkey = test_mk_file_path(certsdir, "serverkey.pem");
6860     if (privkey == NULL) {
6861         OPENSSL_free(cert);
6862         return 0;
6863     }
6864
6865     ADD_TEST(test_large_message_tls);
6866     ADD_TEST(test_large_message_tls_read_ahead);
6867 #ifndef OPENSSL_NO_DTLS
6868     ADD_TEST(test_large_message_dtls);
6869 #endif
6870 #ifndef OPENSSL_NO_OCSP
6871     ADD_TEST(test_tlsext_status_type);
6872 #endif
6873     ADD_TEST(test_session_with_only_int_cache);
6874     ADD_TEST(test_session_with_only_ext_cache);
6875     ADD_TEST(test_session_with_both_cache);
6876 #ifndef OPENSSL_NO_TLS1_3
6877     ADD_ALL_TESTS(test_stateful_tickets, 3);
6878     ADD_ALL_TESTS(test_stateless_tickets, 3);
6879     ADD_TEST(test_psk_tickets);
6880 #endif
6881     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
6882     ADD_TEST(test_ssl_bio_pop_next_bio);
6883     ADD_TEST(test_ssl_bio_pop_ssl_bio);
6884     ADD_TEST(test_ssl_bio_change_rbio);
6885     ADD_TEST(test_ssl_bio_change_wbio);
6886 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
6887     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
6888     ADD_TEST(test_keylog);
6889 #endif
6890 #ifndef OPENSSL_NO_TLS1_3
6891     ADD_TEST(test_keylog_no_master_key);
6892 #endif
6893 #ifndef OPENSSL_NO_TLS1_2
6894     ADD_TEST(test_client_hello_cb);
6895     ADD_TEST(test_ccs_change_cipher);
6896 #endif
6897 #ifndef OPENSSL_NO_TLS1_3
6898     ADD_ALL_TESTS(test_early_data_read_write, 3);
6899     /*
6900      * We don't do replay tests for external PSK. Replay protection isn't used
6901      * in that scenario.
6902      */
6903     ADD_ALL_TESTS(test_early_data_replay, 2);
6904     ADD_ALL_TESTS(test_early_data_skip, 3);
6905     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
6906     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, 3);
6907     ADD_ALL_TESTS(test_early_data_skip_abort, 3);
6908     ADD_ALL_TESTS(test_early_data_not_sent, 3);
6909     ADD_ALL_TESTS(test_early_data_psk, 8);
6910     ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 5);
6911     ADD_ALL_TESTS(test_early_data_not_expected, 3);
6912 # ifndef OPENSSL_NO_TLS1_2
6913     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
6914 # endif
6915 #endif
6916 #ifndef OPENSSL_NO_TLS1_3
6917     ADD_ALL_TESTS(test_set_ciphersuite, 10);
6918     ADD_TEST(test_ciphersuite_change);
6919     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
6920 #ifdef OPENSSL_NO_PSK
6921     ADD_ALL_TESTS(test_tls13_psk, 1);
6922 #else
6923     ADD_ALL_TESTS(test_tls13_psk, 4);
6924 #endif  /* OPENSSL_NO_PSK */
6925     ADD_ALL_TESTS(test_custom_exts, 5);
6926     ADD_TEST(test_stateless);
6927     ADD_TEST(test_pha_key_update);
6928 #else
6929     ADD_ALL_TESTS(test_custom_exts, 3);
6930 #endif
6931     ADD_ALL_TESTS(test_serverinfo, 8);
6932     ADD_ALL_TESTS(test_export_key_mat, 6);
6933 #ifndef OPENSSL_NO_TLS1_3
6934     ADD_ALL_TESTS(test_export_key_mat_early, 3);
6935     ADD_TEST(test_key_update);
6936     ADD_ALL_TESTS(test_key_update_in_write, 2);
6937 #endif
6938     ADD_ALL_TESTS(test_ssl_clear, 2);
6939     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
6940 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
6941     ADD_ALL_TESTS(test_srp, 6);
6942 #endif
6943     ADD_ALL_TESTS(test_info_callback, 6);
6944     ADD_ALL_TESTS(test_ssl_pending, 2);
6945     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
6946     ADD_ALL_TESTS(test_ticket_callbacks, 12);
6947     ADD_ALL_TESTS(test_shutdown, 7);
6948     ADD_ALL_TESTS(test_cert_cb, 6);
6949     ADD_ALL_TESTS(test_client_cert_cb, 2);
6950     ADD_ALL_TESTS(test_ca_names, 3);
6951     ADD_ALL_TESTS(test_servername, 10);
6952 #ifndef OPENSSL_NO_TLS1_2
6953     ADD_TEST(test_ssl_dup);
6954 #endif
6955 #ifndef OPENSSL_NO_TLS1_3
6956     ADD_TEST(test_sni_tls13);
6957 #endif
6958     ADD_TEST(test_set_alpn);
6959     ADD_TEST(test_inherit_verify_param);
6960     return 1;
6961 }
6962
6963 void cleanup_tests(void)
6964 {
6965     OPENSSL_free(cert);
6966     OPENSSL_free(privkey);
6967     bio_s_mempacket_test_free();
6968     bio_s_always_retry_free();
6969 }