7197e15cac4c52a4a58488e7ddedc456b3d183b5
[openssl.git] / test / sslapitest.c
1 /*
2  * Copyright 2016-2022 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 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
4114 {
4115     return 1;
4116 }
4117
4118 /*
4119  * Custom call back tests.
4120  * Test 0: Old style callbacks in TLSv1.2
4121  * Test 1: New style callbacks in TLSv1.2
4122  * Test 2: New style callbacks in TLSv1.2 with SNI
4123  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
4124  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
4125  * Test 5: New style callbacks in TLSv1.3. Extensions in CR + Client Cert
4126  */
4127 static int test_custom_exts(int tst)
4128 {
4129     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
4130     SSL *clientssl = NULL, *serverssl = NULL;
4131     int testresult = 0;
4132     static int server = 1;
4133     static int client = 0;
4134     SSL_SESSION *sess = NULL;
4135     unsigned int context;
4136
4137 #if defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_3)
4138     /* Skip tests for TLSv1.2 and below in this case */
4139     if (tst < 3)
4140         return 1;
4141 #endif
4142
4143     /* Reset callback counters */
4144     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
4145     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
4146     snicb = 0;
4147
4148     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4149                                        TLS1_VERSION, TLS_MAX_VERSION,
4150                                        &sctx, &cctx, cert, privkey)))
4151         goto end;
4152
4153     if (tst == 2
4154             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL,
4155                                               TLS1_VERSION, TLS_MAX_VERSION,
4156                                               &sctx2, NULL, cert, privkey)))
4157         goto end;
4158
4159
4160     if (tst < 3) {
4161         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
4162         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
4163         if (sctx2 != NULL)
4164             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
4165     }
4166
4167     if (tst == 5) {
4168         context = SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
4169                   | SSL_EXT_TLS1_3_CERTIFICATE;
4170         SSL_CTX_set_verify(sctx,
4171                            SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
4172                            verify_cb);
4173         if (!TEST_int_eq(SSL_CTX_use_certificate_file(cctx, cert,
4174                                                       SSL_FILETYPE_PEM), 1)
4175                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(cctx, privkey,
4176                                                             SSL_FILETYPE_PEM), 1)
4177                 || !TEST_int_eq(SSL_CTX_check_private_key(cctx), 1))
4178             goto end;
4179     } else if (tst == 4) {
4180         context = SSL_EXT_CLIENT_HELLO
4181                   | SSL_EXT_TLS1_2_SERVER_HELLO
4182                   | SSL_EXT_TLS1_3_SERVER_HELLO
4183                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
4184                   | SSL_EXT_TLS1_3_CERTIFICATE
4185                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
4186     } else {
4187         context = SSL_EXT_CLIENT_HELLO
4188                   | SSL_EXT_TLS1_2_SERVER_HELLO
4189                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
4190     }
4191
4192     /* Create a client side custom extension */
4193     if (tst == 0) {
4194         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
4195                                                      old_add_cb, old_free_cb,
4196                                                      &client, old_parse_cb,
4197                                                      &client)))
4198             goto end;
4199     } else {
4200         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
4201                                               new_add_cb, new_free_cb,
4202                                               &client, new_parse_cb, &client)))
4203             goto end;
4204     }
4205
4206     /* Should not be able to add duplicates */
4207     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
4208                                                   old_add_cb, old_free_cb,
4209                                                   &client, old_parse_cb,
4210                                                   &client))
4211             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
4212                                                   context, new_add_cb,
4213                                                   new_free_cb, &client,
4214                                                   new_parse_cb, &client)))
4215         goto end;
4216
4217     /* Create a server side custom extension */
4218     if (tst == 0) {
4219         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
4220                                                      old_add_cb, old_free_cb,
4221                                                      &server, old_parse_cb,
4222                                                      &server)))
4223             goto end;
4224     } else {
4225         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
4226                                               new_add_cb, new_free_cb,
4227                                               &server, new_parse_cb, &server)))
4228             goto end;
4229         if (sctx2 != NULL
4230                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
4231                                                      context, new_add_cb,
4232                                                      new_free_cb, &server,
4233                                                      new_parse_cb, &server)))
4234             goto end;
4235     }
4236
4237     /* Should not be able to add duplicates */
4238     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
4239                                                   old_add_cb, old_free_cb,
4240                                                   &server, old_parse_cb,
4241                                                   &server))
4242             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
4243                                                   context, new_add_cb,
4244                                                   new_free_cb, &server,
4245                                                   new_parse_cb, &server)))
4246         goto end;
4247
4248     if (tst == 2) {
4249         /* Set up SNI */
4250         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
4251                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
4252             goto end;
4253     }
4254
4255     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4256                                       &clientssl, NULL, NULL))
4257             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4258                                                 SSL_ERROR_NONE)))
4259         goto end;
4260
4261     if (tst == 0) {
4262         if (clntaddoldcb != 1
4263                 || clntparseoldcb != 1
4264                 || srvaddoldcb != 1
4265                 || srvparseoldcb != 1)
4266             goto end;
4267     } else if (tst == 1 || tst == 2 || tst == 3) {
4268         if (clntaddnewcb != 1
4269                 || clntparsenewcb != 1
4270                 || srvaddnewcb != 1
4271                 || srvparsenewcb != 1
4272                 || (tst != 2 && snicb != 0)
4273                 || (tst == 2 && snicb != 1))
4274             goto end;
4275     } else if (tst == 5) {
4276         if (clntaddnewcb != 1
4277                 || clntparsenewcb != 1
4278                 || srvaddnewcb != 1
4279                 || srvparsenewcb != 1)
4280             goto end;
4281     } else {
4282         /* In this case there 2 NewSessionTicket messages created */
4283         if (clntaddnewcb != 1
4284                 || clntparsenewcb != 5
4285                 || srvaddnewcb != 5
4286                 || srvparsenewcb != 1)
4287             goto end;
4288     }
4289
4290     sess = SSL_get1_session(clientssl);
4291     SSL_shutdown(clientssl);
4292     SSL_shutdown(serverssl);
4293     SSL_free(serverssl);
4294     SSL_free(clientssl);
4295     serverssl = clientssl = NULL;
4296
4297     if (tst == 3 || tst == 5) {
4298         /* We don't bother with the resumption aspects for these tests */
4299         testresult = 1;
4300         goto end;
4301     }
4302
4303     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4304                                       NULL, NULL))
4305             || !TEST_true(SSL_set_session(clientssl, sess))
4306             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4307                                                SSL_ERROR_NONE)))
4308         goto end;
4309
4310     /*
4311      * For a resumed session we expect to add the ClientHello extension. For the
4312      * old style callbacks we ignore it on the server side because they set
4313      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
4314      * them.
4315      */
4316     if (tst == 0) {
4317         if (clntaddoldcb != 2
4318                 || clntparseoldcb != 1
4319                 || srvaddoldcb != 1
4320                 || srvparseoldcb != 1)
4321             goto end;
4322     } else if (tst == 1 || tst == 2 || tst == 3) {
4323         if (clntaddnewcb != 2
4324                 || clntparsenewcb != 2
4325                 || srvaddnewcb != 2
4326                 || srvparsenewcb != 2)
4327             goto end;
4328     } else {
4329         /*
4330          * No Certificate message extensions in the resumption handshake,
4331          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
4332          */
4333         if (clntaddnewcb != 2
4334                 || clntparsenewcb != 8
4335                 || srvaddnewcb != 8
4336                 || srvparsenewcb != 2)
4337             goto end;
4338     }
4339
4340     testresult = 1;
4341
4342 end:
4343     SSL_SESSION_free(sess);
4344     SSL_free(serverssl);
4345     SSL_free(clientssl);
4346     SSL_CTX_free(sctx2);
4347     SSL_CTX_free(sctx);
4348     SSL_CTX_free(cctx);
4349     return testresult;
4350 }
4351
4352 /*
4353  * Test loading of serverinfo data in various formats. test_sslmessages actually
4354  * tests to make sure the extensions appear in the handshake
4355  */
4356 static int test_serverinfo(int tst)
4357 {
4358     unsigned int version;
4359     unsigned char *sibuf;
4360     size_t sibuflen;
4361     int ret, expected, testresult = 0;
4362     SSL_CTX *ctx;
4363
4364     ctx = SSL_CTX_new(TLS_method());
4365     if (!TEST_ptr(ctx))
4366         goto end;
4367
4368     if ((tst & 0x01) == 0x01)
4369         version = SSL_SERVERINFOV2;
4370     else
4371         version = SSL_SERVERINFOV1;
4372
4373     if ((tst & 0x02) == 0x02) {
4374         sibuf = serverinfov2;
4375         sibuflen = sizeof(serverinfov2);
4376         expected = (version == SSL_SERVERINFOV2);
4377     } else {
4378         sibuf = serverinfov1;
4379         sibuflen = sizeof(serverinfov1);
4380         expected = (version == SSL_SERVERINFOV1);
4381     }
4382
4383     if ((tst & 0x04) == 0x04) {
4384         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
4385     } else {
4386         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
4387
4388         /*
4389          * The version variable is irrelevant in this case - it's what is in the
4390          * buffer that matters
4391          */
4392         if ((tst & 0x02) == 0x02)
4393             expected = 0;
4394         else
4395             expected = 1;
4396     }
4397
4398     if (!TEST_true(ret == expected))
4399         goto end;
4400
4401     testresult = 1;
4402
4403  end:
4404     SSL_CTX_free(ctx);
4405
4406     return testresult;
4407 }
4408
4409 /*
4410  * Test that SSL_export_keying_material() produces expected results. There are
4411  * no test vectors so all we do is test that both sides of the communication
4412  * produce the same results for different protocol versions.
4413  */
4414 #define SMALL_LABEL_LEN 10
4415 #define LONG_LABEL_LEN  249
4416 static int test_export_key_mat(int tst)
4417 {
4418     int testresult = 0;
4419     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
4420     SSL *clientssl = NULL, *serverssl = NULL;
4421     const char label[LONG_LABEL_LEN + 1] = "test label";
4422     const unsigned char context[] = "context";
4423     const unsigned char *emptycontext = NULL;
4424     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
4425     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
4426     size_t labellen;
4427     const int protocols[] = {
4428         TLS1_VERSION,
4429         TLS1_1_VERSION,
4430         TLS1_2_VERSION,
4431         TLS1_3_VERSION,
4432         TLS1_3_VERSION,
4433         TLS1_3_VERSION
4434     };
4435
4436 #ifdef OPENSSL_NO_TLS1
4437     if (tst == 0)
4438         return 1;
4439 #endif
4440 #ifdef OPENSSL_NO_TLS1_1
4441     if (tst == 1)
4442         return 1;
4443 #endif
4444 #ifdef OPENSSL_NO_TLS1_2
4445     if (tst == 2)
4446         return 1;
4447 #endif
4448 #ifdef OPENSSL_NO_TLS1_3
4449     if (tst >= 3)
4450         return 1;
4451 #endif
4452     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4453                                        TLS1_VERSION, TLS_MAX_VERSION,
4454                                        &sctx, &cctx, cert, privkey)))
4455         goto end;
4456
4457     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
4458     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
4459     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
4460
4461     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
4462                                       NULL)))
4463         goto end;
4464
4465     /*
4466      * Premature call of SSL_export_keying_material should just fail.
4467      */
4468     if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
4469                                                 sizeof(ckeymat1), label,
4470                                                 SMALL_LABEL_LEN + 1, context,
4471                                                 sizeof(context) - 1, 1), 0))
4472         goto end;
4473
4474     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4475                                          SSL_ERROR_NONE)))
4476         goto end;
4477
4478     if (tst == 5) {
4479         /*
4480          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
4481          * go over that.
4482          */
4483         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
4484                                                     sizeof(ckeymat1), label,
4485                                                     LONG_LABEL_LEN + 1, context,
4486                                                     sizeof(context) - 1, 1), 0))
4487             goto end;
4488
4489         testresult = 1;
4490         goto end;
4491     } else if (tst == 4) {
4492         labellen = LONG_LABEL_LEN;
4493     } else {
4494         labellen = SMALL_LABEL_LEN;
4495     }
4496
4497     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
4498                                                 sizeof(ckeymat1), label,
4499                                                 labellen, context,
4500                                                 sizeof(context) - 1, 1), 1)
4501             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
4502                                                        sizeof(ckeymat2), label,
4503                                                        labellen,
4504                                                        emptycontext,
4505                                                        0, 1), 1)
4506             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
4507                                                        sizeof(ckeymat3), label,
4508                                                        labellen,
4509                                                        NULL, 0, 0), 1)
4510             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
4511                                                        sizeof(skeymat1), label,
4512                                                        labellen,
4513                                                        context,
4514                                                        sizeof(context) -1, 1),
4515                             1)
4516             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
4517                                                        sizeof(skeymat2), label,
4518                                                        labellen,
4519                                                        emptycontext,
4520                                                        0, 1), 1)
4521             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
4522                                                        sizeof(skeymat3), label,
4523                                                        labellen,
4524                                                        NULL, 0, 0), 1)
4525                /*
4526                 * Check that both sides created the same key material with the
4527                 * same context.
4528                 */
4529             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
4530                             sizeof(skeymat1))
4531                /*
4532                 * Check that both sides created the same key material with an
4533                 * empty context.
4534                 */
4535             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
4536                             sizeof(skeymat2))
4537                /*
4538                 * Check that both sides created the same key material without a
4539                 * context.
4540                 */
4541             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
4542                             sizeof(skeymat3))
4543                /* Different contexts should produce different results */
4544             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
4545                             sizeof(ckeymat2)))
4546         goto end;
4547
4548     /*
4549      * Check that an empty context and no context produce different results in
4550      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
4551      */
4552     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
4553                                   sizeof(ckeymat3)))
4554             || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
4555                                          sizeof(ckeymat3))))
4556         goto end;
4557
4558     testresult = 1;
4559
4560  end:
4561     SSL_free(serverssl);
4562     SSL_free(clientssl);
4563     SSL_CTX_free(sctx2);
4564     SSL_CTX_free(sctx);
4565     SSL_CTX_free(cctx);
4566
4567     return testresult;
4568 }
4569
4570 #ifndef OPENSSL_NO_TLS1_3
4571 /*
4572  * Test that SSL_export_keying_material_early() produces expected
4573  * results. There are no test vectors so all we do is test that both
4574  * sides of the communication produce the same results for different
4575  * protocol versions.
4576  */
4577 static int test_export_key_mat_early(int idx)
4578 {
4579     static const char label[] = "test label";
4580     static const unsigned char context[] = "context";
4581     int testresult = 0;
4582     SSL_CTX *cctx = NULL, *sctx = NULL;
4583     SSL *clientssl = NULL, *serverssl = NULL;
4584     SSL_SESSION *sess = NULL;
4585     const unsigned char *emptycontext = NULL;
4586     unsigned char ckeymat1[80], ckeymat2[80];
4587     unsigned char skeymat1[80], skeymat2[80];
4588     unsigned char buf[1];
4589     size_t readbytes, written;
4590
4591     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
4592                                         &sess, idx)))
4593         goto end;
4594
4595     /* Here writing 0 length early data is enough. */
4596     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
4597             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4598                                                 &readbytes),
4599                             SSL_READ_EARLY_DATA_ERROR)
4600             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4601                             SSL_EARLY_DATA_ACCEPTED))
4602         goto end;
4603
4604     if (!TEST_int_eq(SSL_export_keying_material_early(
4605                      clientssl, ckeymat1, sizeof(ckeymat1), label,
4606                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
4607             || !TEST_int_eq(SSL_export_keying_material_early(
4608                             clientssl, ckeymat2, sizeof(ckeymat2), label,
4609                             sizeof(label) - 1, emptycontext, 0), 1)
4610             || !TEST_int_eq(SSL_export_keying_material_early(
4611                             serverssl, skeymat1, sizeof(skeymat1), label,
4612                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
4613             || !TEST_int_eq(SSL_export_keying_material_early(
4614                             serverssl, skeymat2, sizeof(skeymat2), label,
4615                             sizeof(label) - 1, emptycontext, 0), 1)
4616                /*
4617                 * Check that both sides created the same key material with the
4618                 * same context.
4619                 */
4620             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
4621                             sizeof(skeymat1))
4622                /*
4623                 * Check that both sides created the same key material with an
4624                 * empty context.
4625                 */
4626             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
4627                             sizeof(skeymat2))
4628                /* Different contexts should produce different results */
4629             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
4630                             sizeof(ckeymat2)))
4631         goto end;
4632
4633     testresult = 1;
4634
4635  end:
4636     SSL_SESSION_free(sess);
4637     SSL_SESSION_free(clientpsk);
4638     SSL_SESSION_free(serverpsk);
4639     clientpsk = serverpsk = NULL;
4640     SSL_free(serverssl);
4641     SSL_free(clientssl);
4642     SSL_CTX_free(sctx);
4643     SSL_CTX_free(cctx);
4644
4645     return testresult;
4646 }
4647
4648 #define NUM_KEY_UPDATE_MESSAGES 40
4649 /*
4650  * Test KeyUpdate.
4651  */
4652 static int test_key_update(void)
4653 {
4654     SSL_CTX *cctx = NULL, *sctx = NULL;
4655     SSL *clientssl = NULL, *serverssl = NULL;
4656     int testresult = 0, i, j;
4657     char buf[20];
4658     static char *mess = "A test message";
4659
4660     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4661                                        TLS_client_method(),
4662                                        TLS1_3_VERSION,
4663                                        0,
4664                                        &sctx, &cctx, cert, privkey))
4665             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4666                                              NULL, NULL))
4667             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4668                                                 SSL_ERROR_NONE)))
4669         goto end;
4670
4671     for (j = 0; j < 2; j++) {
4672         /* Send lots of KeyUpdate messages */
4673         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
4674             if (!TEST_true(SSL_key_update(clientssl,
4675                                           (j == 0)
4676                                           ? SSL_KEY_UPDATE_NOT_REQUESTED
4677                                           : SSL_KEY_UPDATE_REQUESTED))
4678                     || !TEST_true(SSL_do_handshake(clientssl)))
4679                 goto end;
4680         }
4681
4682         /* Check that sending and receiving app data is ok */
4683         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
4684                 || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
4685                                          strlen(mess)))
4686             goto end;
4687
4688         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
4689                 || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
4690                                          strlen(mess)))
4691             goto end;
4692     }
4693
4694     testresult = 1;
4695
4696  end:
4697     SSL_free(serverssl);
4698     SSL_free(clientssl);
4699     SSL_CTX_free(sctx);
4700     SSL_CTX_free(cctx);
4701
4702     return testresult;
4703 }
4704
4705 /*
4706  * Test we can handle a KeyUpdate (update requested) message while write data
4707  * is pending.
4708  * Test 0: Client sends KeyUpdate while Server is writing
4709  * Test 1: Server sends KeyUpdate while Client is writing
4710  */
4711 static int test_key_update_in_write(int tst)
4712 {
4713     SSL_CTX *cctx = NULL, *sctx = NULL;
4714     SSL *clientssl = NULL, *serverssl = NULL;
4715     int testresult = 0;
4716     char buf[20];
4717     static char *mess = "A test message";
4718     BIO *bretry = BIO_new(bio_s_always_retry());
4719     BIO *tmp = NULL;
4720     SSL *peerupdate = NULL, *peerwrite = NULL;
4721
4722     if (!TEST_ptr(bretry)
4723             || !TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4724                                               TLS_client_method(),
4725                                               TLS1_3_VERSION,
4726                                               0,
4727                                               &sctx, &cctx, cert, privkey))
4728             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4729                                              NULL, NULL))
4730             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4731                                                 SSL_ERROR_NONE)))
4732         goto end;
4733
4734     peerupdate = tst == 0 ? clientssl : serverssl;
4735     peerwrite = tst == 0 ? serverssl : clientssl;
4736
4737     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
4738             || !TEST_true(SSL_do_handshake(peerupdate)))
4739         goto end;
4740
4741     /* Swap the writing endpoint's write BIO to force a retry */
4742     tmp = SSL_get_wbio(peerwrite);
4743     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
4744         tmp = NULL;
4745         goto end;
4746     }
4747     SSL_set0_wbio(peerwrite, bretry);
4748     bretry = NULL;
4749
4750     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
4751     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
4752             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE))
4753         goto end;
4754
4755     /* Reinstate the original writing endpoint's write BIO */
4756     SSL_set0_wbio(peerwrite, tmp);
4757     tmp = NULL;
4758
4759     /* Now read some data - we will read the key update */
4760     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
4761             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ))
4762         goto end;
4763
4764     /*
4765      * Complete the write we started previously and read it from the other
4766      * endpoint
4767      */
4768     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
4769             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
4770         goto end;
4771
4772     /* Write more data to ensure we send the KeyUpdate message back */
4773     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
4774             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
4775         goto end;
4776
4777     testresult = 1;
4778
4779  end:
4780     SSL_free(serverssl);
4781     SSL_free(clientssl);
4782     SSL_CTX_free(sctx);
4783     SSL_CTX_free(cctx);
4784     BIO_free(bretry);
4785     BIO_free(tmp);
4786
4787     return testresult;
4788 }
4789 #endif /* OPENSSL_NO_TLS1_3 */
4790
4791 static int test_ssl_clear(int idx)
4792 {
4793     SSL_CTX *cctx = NULL, *sctx = NULL;
4794     SSL *clientssl = NULL, *serverssl = NULL;
4795     int testresult = 0;
4796
4797 #ifdef OPENSSL_NO_TLS1_2
4798     if (idx == 1)
4799         return 1;
4800 #endif
4801
4802     /* Create an initial connection */
4803     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4804                                        TLS1_VERSION, TLS_MAX_VERSION,
4805                                        &sctx, &cctx, cert, privkey))
4806             || (idx == 1
4807                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
4808                                                             TLS1_2_VERSION)))
4809             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4810                                           &clientssl, NULL, NULL))
4811             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4812                                                 SSL_ERROR_NONE)))
4813         goto end;
4814
4815     SSL_shutdown(clientssl);
4816     SSL_shutdown(serverssl);
4817     SSL_free(serverssl);
4818     serverssl = NULL;
4819
4820     /* Clear clientssl - we're going to reuse the object */
4821     if (!TEST_true(SSL_clear(clientssl)))
4822         goto end;
4823
4824     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4825                                              NULL, NULL))
4826             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4827                                                 SSL_ERROR_NONE))
4828             || !TEST_true(SSL_session_reused(clientssl)))
4829         goto end;
4830
4831     SSL_shutdown(clientssl);
4832     SSL_shutdown(serverssl);
4833
4834     testresult = 1;
4835
4836  end:
4837     SSL_free(serverssl);
4838     SSL_free(clientssl);
4839     SSL_CTX_free(sctx);
4840     SSL_CTX_free(cctx);
4841
4842     return testresult;
4843 }
4844
4845 /* Parse CH and retrieve any MFL extension value if present */
4846 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
4847 {
4848     long len;
4849     unsigned char *data;
4850     PACKET pkt = {0}, pkt2 = {0}, pkt3 = {0};
4851     unsigned int MFL_code = 0, type = 0;
4852
4853     if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
4854         goto end;
4855
4856     if (!TEST_true( PACKET_buf_init( &pkt, data, len ) )
4857                /* Skip the record header */
4858             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
4859                /* Skip the handshake message header */
4860             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
4861                /* Skip client version and random */
4862             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
4863                                                + SSL3_RANDOM_SIZE))
4864                /* Skip session id */
4865             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
4866                /* Skip ciphers */
4867             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
4868                /* Skip compression */
4869             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
4870                /* Extensions len */
4871             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
4872         goto end;
4873
4874     /* Loop through all extensions */
4875     while (PACKET_remaining(&pkt2)) {
4876         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
4877                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
4878             goto end;
4879
4880         if (type == TLSEXT_TYPE_max_fragment_length) {
4881             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
4882                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
4883                 goto end;
4884
4885             *mfl_codemfl_code = MFL_code;
4886             return 1;
4887         }
4888     }
4889
4890  end:
4891     return 0;
4892 }
4893
4894 /* Maximum-Fragment-Length TLS extension mode to test */
4895 static const unsigned char max_fragment_len_test[] = {
4896     TLSEXT_max_fragment_length_512,
4897     TLSEXT_max_fragment_length_1024,
4898     TLSEXT_max_fragment_length_2048,
4899     TLSEXT_max_fragment_length_4096
4900 };
4901
4902 static int test_max_fragment_len_ext(int idx_tst)
4903 {
4904     SSL_CTX *ctx;
4905     SSL *con = NULL;
4906     int testresult = 0, MFL_mode = 0;
4907     BIO *rbio, *wbio;
4908
4909     ctx = SSL_CTX_new(TLS_method());
4910     if (!TEST_ptr(ctx))
4911         goto end;
4912
4913     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
4914                    ctx, max_fragment_len_test[idx_tst])))
4915         goto end;
4916
4917     con = SSL_new(ctx);
4918     if (!TEST_ptr(con))
4919         goto end;
4920
4921     rbio = BIO_new(BIO_s_mem());
4922     wbio = BIO_new(BIO_s_mem());
4923     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
4924         BIO_free(rbio);
4925         BIO_free(wbio);
4926         goto end;
4927     }
4928
4929     SSL_set_bio(con, rbio, wbio);
4930     SSL_set_connect_state(con);
4931
4932     if (!TEST_int_le(SSL_connect(con), 0)) {
4933         /* This shouldn't succeed because we don't have a server! */
4934         goto end;
4935     }
4936
4937     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
4938         /* no MFL in client hello */
4939         goto end;
4940     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
4941         goto end;
4942
4943     testresult = 1;
4944
4945 end:
4946     SSL_free(con);
4947     SSL_CTX_free(ctx);
4948
4949     return testresult;
4950 }
4951
4952 #ifndef OPENSSL_NO_TLS1_3
4953 static int test_pha_key_update(void)
4954 {
4955     SSL_CTX *cctx = NULL, *sctx = NULL;
4956     SSL *clientssl = NULL, *serverssl = NULL;
4957     int testresult = 0;
4958
4959     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4960                                        TLS1_VERSION, TLS_MAX_VERSION,
4961                                        &sctx, &cctx, cert, privkey)))
4962         return 0;
4963
4964     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
4965         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
4966         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
4967         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
4968         goto end;
4969
4970     SSL_CTX_set_post_handshake_auth(cctx, 1);
4971
4972     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4973                                       NULL, NULL)))
4974         goto end;
4975
4976     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4977                                          SSL_ERROR_NONE)))
4978         goto end;
4979
4980     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
4981     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
4982         goto end;
4983
4984     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
4985         goto end;
4986
4987     /* Start handshake on the server */
4988     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
4989         goto end;
4990
4991     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
4992     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4993                                          SSL_ERROR_NONE)))
4994         goto end;
4995
4996     SSL_shutdown(clientssl);
4997     SSL_shutdown(serverssl);
4998
4999     testresult = 1;
5000
5001  end:
5002     SSL_free(serverssl);
5003     SSL_free(clientssl);
5004     SSL_CTX_free(sctx);
5005     SSL_CTX_free(cctx);
5006     return testresult;
5007 }
5008 #endif
5009
5010 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
5011
5012 static SRP_VBASE *vbase = NULL;
5013
5014 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
5015 {
5016     int ret = SSL3_AL_FATAL;
5017     char *username;
5018     SRP_user_pwd *user = NULL;
5019
5020     username = SSL_get_srp_username(s);
5021     if (username == NULL) {
5022         *ad = SSL_AD_INTERNAL_ERROR;
5023         goto err;
5024     }
5025
5026     user = SRP_VBASE_get1_by_user(vbase, username);
5027     if (user == NULL) {
5028         *ad = SSL_AD_INTERNAL_ERROR;
5029         goto err;
5030     }
5031
5032     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
5033                                  user->info) <= 0) {
5034         *ad = SSL_AD_INTERNAL_ERROR;
5035         goto err;
5036     }
5037
5038     ret = 0;
5039
5040  err:
5041     SRP_user_pwd_free(user);
5042     return ret;
5043 }
5044
5045 static int create_new_vfile(char *userid, char *password, const char *filename)
5046 {
5047     char *gNid = NULL;
5048     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
5049     TXT_DB *db = NULL;
5050     int ret = 0;
5051     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
5052     size_t i;
5053
5054     if (!TEST_ptr(dummy) || !TEST_ptr(row))
5055         goto end;
5056
5057     gNid = SRP_create_verifier(userid, password, &row[DB_srpsalt],
5058                                &row[DB_srpverifier], NULL, NULL);
5059     if (!TEST_ptr(gNid))
5060         goto end;
5061
5062     /*
5063      * The only way to create an empty TXT_DB is to provide a BIO with no data
5064      * in it!
5065      */
5066     db = TXT_DB_read(dummy, DB_NUMBER);
5067     if (!TEST_ptr(db))
5068         goto end;
5069
5070     out = BIO_new_file(filename, "w");
5071     if (!TEST_ptr(out))
5072         goto end;
5073
5074     row[DB_srpid] = OPENSSL_strdup(userid);
5075     row[DB_srptype] = OPENSSL_strdup("V");
5076     row[DB_srpgN] = OPENSSL_strdup(gNid);
5077
5078     if (!TEST_ptr(row[DB_srpid])
5079             || !TEST_ptr(row[DB_srptype])
5080             || !TEST_ptr(row[DB_srpgN])
5081             || !TEST_true(TXT_DB_insert(db, row)))
5082         goto end;
5083
5084     row = NULL;
5085
5086     if (!TXT_DB_write(out, db))
5087         goto end;
5088
5089     ret = 1;
5090  end:
5091     if (row != NULL) {
5092         for (i = 0; i < DB_NUMBER; i++)
5093             OPENSSL_free(row[i]);
5094     }
5095     OPENSSL_free(row);
5096     BIO_free(dummy);
5097     BIO_free(out);
5098     TXT_DB_free(db);
5099
5100     return ret;
5101 }
5102
5103 static int create_new_vbase(char *userid, char *password)
5104 {
5105     BIGNUM *verifier = NULL, *salt = NULL;
5106     const SRP_gN *lgN = NULL;
5107     SRP_user_pwd *user_pwd = NULL;
5108     int ret = 0;
5109
5110     lgN = SRP_get_default_gN(NULL);
5111     if (!TEST_ptr(lgN))
5112         goto end;
5113
5114     if (!TEST_true(SRP_create_verifier_BN(userid, password, &salt, &verifier,
5115                                           lgN->N, lgN->g)))
5116         goto end;
5117
5118     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
5119     if (!TEST_ptr(user_pwd))
5120         goto end;
5121
5122     user_pwd->N = lgN->N;
5123     user_pwd->g = lgN->g;
5124     user_pwd->id = OPENSSL_strdup(userid);
5125     if (!TEST_ptr(user_pwd->id))
5126         goto end;
5127
5128     user_pwd->v = verifier;
5129     user_pwd->s = salt;
5130     verifier = salt = NULL;
5131
5132     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
5133         goto end;
5134     user_pwd = NULL;
5135
5136     ret = 1;
5137 end:
5138     SRP_user_pwd_free(user_pwd);
5139     BN_free(salt);
5140     BN_free(verifier);
5141
5142     return ret;
5143 }
5144
5145 /*
5146  * SRP tests
5147  *
5148  * Test 0: Simple successful SRP connection, new vbase
5149  * Test 1: Connection failure due to bad password, new vbase
5150  * Test 2: Simple successful SRP connection, vbase loaded from existing file
5151  * Test 3: Connection failure due to bad password, vbase loaded from existing
5152  *         file
5153  * Test 4: Simple successful SRP connection, vbase loaded from new file
5154  * Test 5: Connection failure due to bad password, vbase loaded from new file
5155  */
5156 static int test_srp(int tst)
5157 {
5158     char *userid = "test", *password = "password", *tstsrpfile;
5159     SSL_CTX *cctx = NULL, *sctx = NULL;
5160     SSL *clientssl = NULL, *serverssl = NULL;
5161     int ret, testresult = 0;
5162
5163     vbase = SRP_VBASE_new(NULL);
5164     if (!TEST_ptr(vbase))
5165         goto end;
5166
5167     if (tst == 0 || tst == 1) {
5168         if (!TEST_true(create_new_vbase(userid, password)))
5169             goto end;
5170     } else {
5171         if (tst == 4 || tst == 5) {
5172             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
5173                 goto end;
5174             tstsrpfile = tmpfilename;
5175         } else {
5176             tstsrpfile = srpvfile;
5177         }
5178         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
5179             goto end;
5180     }
5181
5182     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
5183                                        TLS1_VERSION, TLS_MAX_VERSION,
5184                                        &sctx, &cctx, cert, privkey)))
5185         goto end;
5186
5187     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
5188             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
5189             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
5190             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
5191             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
5192         goto end;
5193
5194     if (tst % 2 == 1) {
5195         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
5196             goto end;
5197     } else {
5198         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
5199             goto end;
5200     }
5201
5202     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5203                                       NULL, NULL)))
5204         goto end;
5205
5206     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
5207     if (ret) {
5208         if (!TEST_true(tst % 2 == 0))
5209             goto end;
5210     } else {
5211         if (!TEST_true(tst % 2 == 1))
5212             goto end;
5213     }
5214
5215     testresult = 1;
5216
5217  end:
5218     SRP_VBASE_free(vbase);
5219     vbase = NULL;
5220     SSL_free(serverssl);
5221     SSL_free(clientssl);
5222     SSL_CTX_free(sctx);
5223     SSL_CTX_free(cctx);
5224
5225     return testresult;
5226 }
5227 #endif
5228
5229 static int info_cb_failed = 0;
5230 static int info_cb_offset = 0;
5231 static int info_cb_this_state = -1;
5232
5233 static struct info_cb_states_st {
5234     int where;
5235     const char *statestr;
5236 } info_cb_states[][60] = {
5237     {
5238         /* TLSv1.2 server followed by resumption */
5239         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5240         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5241         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
5242         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
5243         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
5244         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5245         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5246         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
5247         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
5248         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5249         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
5250         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5251         {SSL_CB_EXIT, NULL}, {0, NULL},
5252     }, {
5253         /* TLSv1.2 client followed by resumption */
5254         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5255         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5256         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
5257         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
5258         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
5259         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
5260         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
5261         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5262         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5263         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
5264         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
5265         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
5266     }, {
5267         /* TLSv1.3 server followed by resumption */
5268         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5269         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5270         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
5271         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
5272         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
5273         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
5274         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
5275         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5276         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5277         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
5278         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
5279         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5280         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
5281     }, {
5282         /* TLSv1.3 client followed by resumption */
5283         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5284         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5285         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
5286         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
5287         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
5288         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
5289         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "},
5290         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
5291         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
5292         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
5293         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
5294         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5295         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5296         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
5297         {SSL_CB_EXIT, NULL}, {0, NULL},
5298     }, {
5299         /* TLSv1.3 server, early_data */
5300         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5301         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5302         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
5303         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5304         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
5305         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
5306         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
5307         {SSL_CB_EXIT, NULL}, {0, NULL},
5308     }, {
5309         /* TLSv1.3 client, early_data */
5310         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5311         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
5312         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5313         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
5314         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
5315         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
5316         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5317         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
5318         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
5319     }, {
5320         {0, NULL},
5321     }
5322 };
5323
5324 static void sslapi_info_callback(const SSL *s, int where, int ret)
5325 {
5326     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
5327
5328     /* We do not ever expect a connection to fail in this test */
5329     if (!TEST_false(ret == 0)) {
5330         info_cb_failed = 1;
5331         return;
5332     }
5333
5334     /*
5335      * Do some sanity checks. We never expect these things to happen in this
5336      * test
5337      */
5338     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
5339             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
5340             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
5341         info_cb_failed = 1;
5342         return;
5343     }
5344
5345     /* Now check we're in the right state */
5346     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
5347         info_cb_failed = 1;
5348         return;
5349     }
5350     if ((where & SSL_CB_LOOP) != 0
5351             && !TEST_int_eq(strcmp(SSL_state_string(s),
5352                             state[info_cb_this_state].statestr), 0)) {
5353         info_cb_failed = 1;
5354         return;
5355     }
5356
5357     /*
5358      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
5359      */
5360     if ((where & SSL_CB_HANDSHAKE_DONE)
5361             && SSL_in_init((SSL *)s) != 0) {
5362         info_cb_failed = 1;
5363         return;
5364     }
5365 }
5366
5367 /*
5368  * Test the info callback gets called when we expect it to.
5369  *
5370  * Test 0: TLSv1.2, server
5371  * Test 1: TLSv1.2, client
5372  * Test 2: TLSv1.3, server
5373  * Test 3: TLSv1.3, client
5374  * Test 4: TLSv1.3, server, early_data
5375  * Test 5: TLSv1.3, client, early_data
5376  */
5377 static int test_info_callback(int tst)
5378 {
5379     SSL_CTX *cctx = NULL, *sctx = NULL;
5380     SSL *clientssl = NULL, *serverssl = NULL;
5381     SSL_SESSION *clntsess = NULL;
5382     int testresult = 0;
5383     int tlsvers;
5384
5385     if (tst < 2) {
5386 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
5387 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
5388                                     || !defined(OPENSSL_NO_DH))
5389         tlsvers = TLS1_2_VERSION;
5390 #else
5391         return 1;
5392 #endif
5393     } else {
5394 #ifndef OPENSSL_NO_TLS1_3
5395         tlsvers = TLS1_3_VERSION;
5396 #else
5397         return 1;
5398 #endif
5399     }
5400
5401     /* Reset globals */
5402     info_cb_failed = 0;
5403     info_cb_this_state = -1;
5404     info_cb_offset = tst;
5405
5406 #ifndef OPENSSL_NO_TLS1_3
5407     if (tst >= 4) {
5408         SSL_SESSION *sess = NULL;
5409         size_t written, readbytes;
5410         unsigned char buf[80];
5411
5412         /* early_data tests */
5413         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
5414                                             &serverssl, &sess, 0)))
5415             goto end;
5416
5417         /* We don't actually need this reference */
5418         SSL_SESSION_free(sess);
5419
5420         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
5421                               sslapi_info_callback);
5422
5423         /* Write and read some early data and then complete the connection */
5424         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
5425                                             &written))
5426                 || !TEST_size_t_eq(written, strlen(MSG1))
5427                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
5428                                                     sizeof(buf), &readbytes),
5429                                 SSL_READ_EARLY_DATA_SUCCESS)
5430                 || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
5431                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
5432                                 SSL_EARLY_DATA_ACCEPTED)
5433                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
5434                                                     SSL_ERROR_NONE))
5435                 || !TEST_false(info_cb_failed))
5436             goto end;
5437
5438         testresult = 1;
5439         goto end;
5440     }
5441 #endif
5442
5443     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5444                                        TLS_client_method(),
5445                                        tlsvers, tlsvers, &sctx, &cctx, cert,
5446                                        privkey)))
5447         goto end;
5448
5449     /*
5450      * For even numbered tests we check the server callbacks. For odd numbers we
5451      * check the client.
5452      */
5453     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
5454                               sslapi_info_callback);
5455
5456     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5457                                           &clientssl, NULL, NULL))
5458         || !TEST_true(create_ssl_connection(serverssl, clientssl,
5459                                             SSL_ERROR_NONE))
5460         || !TEST_false(info_cb_failed))
5461     goto end;
5462
5463
5464
5465     clntsess = SSL_get1_session(clientssl);
5466     SSL_shutdown(clientssl);
5467     SSL_shutdown(serverssl);
5468     SSL_free(serverssl);
5469     SSL_free(clientssl);
5470     serverssl = clientssl = NULL;
5471
5472     /* Now do a resumption */
5473     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
5474                                       NULL))
5475             || !TEST_true(SSL_set_session(clientssl, clntsess))
5476             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5477                                                 SSL_ERROR_NONE))
5478             || !TEST_true(SSL_session_reused(clientssl))
5479             || !TEST_false(info_cb_failed))
5480         goto end;
5481
5482     testresult = 1;
5483
5484  end:
5485     SSL_free(serverssl);
5486     SSL_free(clientssl);
5487     SSL_SESSION_free(clntsess);
5488     SSL_CTX_free(sctx);
5489     SSL_CTX_free(cctx);
5490     return testresult;
5491 }
5492
5493 static int test_ssl_pending(int tst)
5494 {
5495     SSL_CTX *cctx = NULL, *sctx = NULL;
5496     SSL *clientssl = NULL, *serverssl = NULL;
5497     int testresult = 0;
5498     char msg[] = "A test message";
5499     char buf[5];
5500     size_t written, readbytes;
5501
5502     if (tst == 0) {
5503         if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5504                                            TLS_client_method(),
5505                                            TLS1_VERSION, TLS_MAX_VERSION,
5506                                            &sctx, &cctx, cert, privkey)))
5507             goto end;
5508     } else {
5509 #ifndef OPENSSL_NO_DTLS
5510         if (!TEST_true(create_ssl_ctx_pair(DTLS_server_method(),
5511                                            DTLS_client_method(),
5512                                            DTLS1_VERSION, DTLS_MAX_VERSION,
5513                                            &sctx, &cctx, cert, privkey)))
5514             goto end;
5515 #else
5516         return 1;
5517 #endif
5518     }
5519
5520     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5521                                              NULL, NULL))
5522             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5523                                                 SSL_ERROR_NONE)))
5524         goto end;
5525
5526     if (!TEST_int_eq(SSL_pending(clientssl), 0)
5527             || !TEST_false(SSL_has_pending(clientssl))
5528             || !TEST_int_eq(SSL_pending(serverssl), 0)
5529             || !TEST_false(SSL_has_pending(serverssl))
5530             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
5531             || !TEST_size_t_eq(written, sizeof(msg))
5532             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
5533             || !TEST_size_t_eq(readbytes, sizeof(buf))
5534             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
5535             || !TEST_true(SSL_has_pending(clientssl)))
5536         goto end;
5537
5538     testresult = 1;
5539
5540  end:
5541     SSL_free(serverssl);
5542     SSL_free(clientssl);
5543     SSL_CTX_free(sctx);
5544     SSL_CTX_free(cctx);
5545
5546     return testresult;
5547 }
5548
5549 static struct {
5550     unsigned int maxprot;
5551     const char *clntciphers;
5552     const char *clnttls13ciphers;
5553     const char *srvrciphers;
5554     const char *srvrtls13ciphers;
5555     const char *shared;
5556 } shared_ciphers_data[] = {
5557 /*
5558  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
5559  * TLSv1.3 is enabled but TLSv1.2 is disabled.
5560  */
5561 #if defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
5562     {
5563         TLS1_2_VERSION,
5564         "AES128-SHA:AES256-SHA",
5565         NULL,
5566         "AES256-SHA:DHE-RSA-AES128-SHA",
5567         NULL,
5568         "AES256-SHA"
5569     },
5570     {
5571         TLS1_2_VERSION,
5572         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
5573         NULL,
5574         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
5575         NULL,
5576         "AES128-SHA:AES256-SHA"
5577     },
5578     {
5579         TLS1_2_VERSION,
5580         "AES128-SHA:AES256-SHA",
5581         NULL,
5582         "AES128-SHA:DHE-RSA-AES128-SHA",
5583         NULL,
5584         "AES128-SHA"
5585     },
5586 #endif
5587 /*
5588  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
5589  * enabled.
5590  */
5591 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
5592     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
5593     {
5594         TLS1_3_VERSION,
5595         "AES128-SHA:AES256-SHA",
5596         NULL,
5597         "AES256-SHA:AES128-SHA256",
5598         NULL,
5599         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
5600         "TLS_AES_128_GCM_SHA256:AES256-SHA"
5601     },
5602 #endif
5603 #ifndef OPENSSL_NO_TLS1_3
5604     {
5605         TLS1_3_VERSION,
5606         "AES128-SHA",
5607         "TLS_AES_256_GCM_SHA384",
5608         "AES256-SHA",
5609         "TLS_AES_256_GCM_SHA384",
5610         "TLS_AES_256_GCM_SHA384"
5611     },
5612 #endif
5613 };
5614
5615 static int test_ssl_get_shared_ciphers(int tst)
5616 {
5617     SSL_CTX *cctx = NULL, *sctx = NULL;
5618     SSL *clientssl = NULL, *serverssl = NULL;
5619     int testresult = 0;
5620     char buf[1024];
5621
5622     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5623                                        TLS_client_method(),
5624                                        TLS1_VERSION,
5625                                        shared_ciphers_data[tst].maxprot,
5626                                        &sctx, &cctx, cert, privkey)))
5627         goto end;
5628
5629     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5630                                         shared_ciphers_data[tst].clntciphers))
5631             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
5632                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
5633                                     shared_ciphers_data[tst].clnttls13ciphers)))
5634             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
5635                                         shared_ciphers_data[tst].srvrciphers))
5636             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
5637                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
5638                                     shared_ciphers_data[tst].srvrtls13ciphers))))
5639         goto end;
5640
5641
5642     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5643                                              NULL, NULL))
5644             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5645                                                 SSL_ERROR_NONE)))
5646         goto end;
5647
5648     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
5649             || !TEST_int_eq(strcmp(buf, shared_ciphers_data[tst].shared), 0)) {
5650         TEST_info("Shared ciphers are: %s\n", buf);
5651         goto end;
5652     }
5653
5654     testresult = 1;
5655
5656  end:
5657     SSL_free(serverssl);
5658     SSL_free(clientssl);
5659     SSL_CTX_free(sctx);
5660     SSL_CTX_free(cctx);
5661
5662     return testresult;
5663 }
5664
5665 static const char *appdata = "Hello World";
5666 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
5667 static int tick_key_renew = 0;
5668 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
5669
5670 static int gen_tick_cb(SSL *s, void *arg)
5671 {
5672     gen_tick_called = 1;
5673
5674     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
5675                                            strlen(appdata));
5676 }
5677
5678 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
5679                                      const unsigned char *keyname,
5680                                      size_t keyname_length,
5681                                      SSL_TICKET_STATUS status,
5682                                      void *arg)
5683 {
5684     void *tickdata;
5685     size_t tickdlen;
5686
5687     dec_tick_called = 1;
5688
5689     if (status == SSL_TICKET_EMPTY)
5690         return SSL_TICKET_RETURN_IGNORE_RENEW;
5691
5692     if (!TEST_true(status == SSL_TICKET_SUCCESS
5693                    || status == SSL_TICKET_SUCCESS_RENEW))
5694         return SSL_TICKET_RETURN_ABORT;
5695
5696     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
5697                                                    &tickdlen))
5698             || !TEST_size_t_eq(tickdlen, strlen(appdata))
5699             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
5700         return SSL_TICKET_RETURN_ABORT;
5701
5702     if (tick_key_cb_called)  {
5703         /* Don't change what the ticket key callback wanted to do */
5704         switch (status) {
5705         case SSL_TICKET_NO_DECRYPT:
5706             return SSL_TICKET_RETURN_IGNORE_RENEW;
5707
5708         case SSL_TICKET_SUCCESS:
5709             return SSL_TICKET_RETURN_USE;
5710
5711         case SSL_TICKET_SUCCESS_RENEW:
5712             return SSL_TICKET_RETURN_USE_RENEW;
5713
5714         default:
5715             return SSL_TICKET_RETURN_ABORT;
5716         }
5717     }
5718     return tick_dec_ret;
5719
5720 }
5721
5722 static int tick_key_cb(SSL *s, unsigned char key_name[16],
5723                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
5724                        HMAC_CTX *hctx, int enc)
5725 {
5726     const unsigned char tick_aes_key[16] = "0123456789abcdef";
5727     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
5728
5729     tick_key_cb_called = 1;
5730     memset(iv, 0, AES_BLOCK_SIZE);
5731     memset(key_name, 0, 16);
5732     if (!EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, tick_aes_key, iv, enc)
5733             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key),
5734                              EVP_sha256(), NULL))
5735         return -1;
5736
5737     return tick_key_renew ? 2 : 1;
5738 }
5739
5740 /*
5741  * Test the various ticket callbacks
5742  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
5743  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
5744  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
5745  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
5746  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
5747  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
5748  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
5749  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
5750  * Test 8: TLSv1.2, ticket key callback, ticket, no renewal
5751  * Test 9: TLSv1.3, ticket key callback, ticket, no renewal
5752  * Test 10: TLSv1.2, ticket key callback, ticket, renewal
5753  * Test 11: TLSv1.3, ticket key callback, ticket, renewal
5754  */
5755 static int test_ticket_callbacks(int tst)
5756 {
5757     SSL_CTX *cctx = NULL, *sctx = NULL;
5758     SSL *clientssl = NULL, *serverssl = NULL;
5759     SSL_SESSION *clntsess = NULL;
5760     int testresult = 0;
5761
5762 #ifdef OPENSSL_NO_TLS1_2
5763     if (tst % 2 == 0)
5764         return 1;
5765 #endif
5766 #ifdef OPENSSL_NO_TLS1_3
5767     if (tst % 2 == 1)
5768         return 1;
5769 #endif
5770
5771     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
5772
5773     /* Which tests the ticket key callback should request renewal for */
5774     if (tst == 10 || tst == 11)
5775         tick_key_renew = 1;
5776     else
5777         tick_key_renew = 0;
5778
5779     /* Which tests the decrypt ticket callback should request renewal for */
5780     switch (tst) {
5781     case 0:
5782     case 1:
5783         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
5784         break;
5785
5786     case 2:
5787     case 3:
5788         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
5789         break;
5790
5791     case 4:
5792     case 5:
5793         tick_dec_ret = SSL_TICKET_RETURN_USE;
5794         break;
5795
5796     case 6:
5797     case 7:
5798         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
5799         break;
5800
5801     default:
5802         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
5803     }
5804
5805     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5806                                        TLS_client_method(),
5807                                        TLS1_VERSION,
5808                                        ((tst % 2) == 0) ? TLS1_2_VERSION
5809                                                         : TLS1_3_VERSION,
5810                                        &sctx, &cctx, cert, privkey)))
5811         goto end;
5812
5813     /*
5814      * We only want sessions to resume from tickets - not the session cache. So
5815      * switch the cache off.
5816      */
5817     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
5818         goto end;
5819
5820     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
5821                                                  NULL)))
5822         goto end;
5823
5824     if (tst >= 8
5825             && !TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
5826         goto end;
5827
5828     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5829                                              NULL, NULL))
5830             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5831                                                 SSL_ERROR_NONE)))
5832         goto end;
5833
5834     /*
5835      * The decrypt ticket key callback in TLSv1.2 should be called even though
5836      * we have no ticket yet, because it gets called with a status of
5837      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
5838      * actually send any ticket data). This does not happen in TLSv1.3 because
5839      * it is not valid to send empty ticket data in TLSv1.3.
5840      */
5841     if (!TEST_int_eq(gen_tick_called, 1)
5842             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
5843         goto end;
5844
5845     gen_tick_called = dec_tick_called = 0;
5846
5847     clntsess = SSL_get1_session(clientssl);
5848     SSL_shutdown(clientssl);
5849     SSL_shutdown(serverssl);
5850     SSL_free(serverssl);
5851     SSL_free(clientssl);
5852     serverssl = clientssl = NULL;
5853
5854     /* Now do a resumption */
5855     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
5856                                       NULL))
5857             || !TEST_true(SSL_set_session(clientssl, clntsess))
5858             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5859                                                 SSL_ERROR_NONE)))
5860         goto end;
5861
5862     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
5863             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW) {
5864         if (!TEST_false(SSL_session_reused(clientssl)))
5865             goto end;
5866     } else {
5867         if (!TEST_true(SSL_session_reused(clientssl)))
5868             goto end;
5869     }
5870
5871     if (!TEST_int_eq(gen_tick_called,
5872                      (tick_key_renew
5873                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
5874                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
5875                      ? 1 : 0)
5876             || !TEST_int_eq(dec_tick_called, 1))
5877         goto end;
5878
5879     testresult = 1;
5880
5881  end:
5882     SSL_SESSION_free(clntsess);
5883     SSL_free(serverssl);
5884     SSL_free(clientssl);
5885     SSL_CTX_free(sctx);
5886     SSL_CTX_free(cctx);
5887
5888     return testresult;
5889 }
5890
5891 /*
5892  * Test bi-directional shutdown.
5893  * Test 0: TLSv1.2
5894  * Test 1: TLSv1.2, server continues to read/write after client shutdown
5895  * Test 2: TLSv1.3, no pending NewSessionTicket messages
5896  * Test 3: TLSv1.3, pending NewSessionTicket messages
5897  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
5898  *                  sends key update, client reads it
5899  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
5900  *                  sends CertificateRequest, client reads and ignores it
5901  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
5902  *                  doesn't read it
5903  */
5904 static int test_shutdown(int tst)
5905 {
5906     SSL_CTX *cctx = NULL, *sctx = NULL;
5907     SSL *clientssl = NULL, *serverssl = NULL;
5908     int testresult = 0;
5909     char msg[] = "A test message";
5910     char buf[80];
5911     size_t written, readbytes;
5912     SSL_SESSION *sess;
5913
5914 #ifdef OPENSSL_NO_TLS1_2
5915     if (tst <= 1)
5916         return 1;
5917 #endif
5918 #ifdef OPENSSL_NO_TLS1_3
5919     if (tst >= 2)
5920         return 1;
5921 #endif
5922
5923     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5924                                        TLS_client_method(),
5925                                        TLS1_VERSION,
5926                                        (tst <= 1) ? TLS1_2_VERSION
5927                                                   : TLS1_3_VERSION,
5928                                        &sctx, &cctx, cert, privkey)))
5929         goto end;
5930
5931     if (tst == 5)
5932         SSL_CTX_set_post_handshake_auth(cctx, 1);
5933
5934     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5935                                              NULL, NULL)))
5936         goto end;
5937
5938     if (tst == 3) {
5939         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
5940                                                   SSL_ERROR_NONE, 1))
5941                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
5942                 || !TEST_false(SSL_SESSION_is_resumable(sess)))
5943             goto end;
5944     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5945                                               SSL_ERROR_NONE))
5946             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
5947             || !TEST_true(SSL_SESSION_is_resumable(sess))) {
5948         goto end;
5949     }
5950
5951     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
5952         goto end;
5953
5954     if (tst >= 4) {
5955         /*
5956          * Reading on the server after the client has sent close_notify should
5957          * fail and provide SSL_ERROR_ZERO_RETURN
5958          */
5959         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
5960                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
5961                                 SSL_ERROR_ZERO_RETURN)
5962                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
5963                                 SSL_RECEIVED_SHUTDOWN)
5964                    /*
5965                     * Even though we're shutdown on receive we should still be
5966                     * able to write.
5967                     */
5968                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
5969             goto end;
5970         if (tst == 4
5971                 && !TEST_true(SSL_key_update(serverssl,
5972                                              SSL_KEY_UPDATE_REQUESTED)))
5973             goto end;
5974         if (tst == 5) {
5975             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
5976             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
5977                 goto end;
5978         }
5979         if ((tst == 4 || tst == 5)
5980                 && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
5981             goto end;
5982         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
5983             goto end;
5984         if (tst == 4 || tst == 5) {
5985             /* Should still be able to read data from server */
5986             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
5987                                        &readbytes))
5988                     || !TEST_size_t_eq(readbytes, sizeof(msg))
5989                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
5990                     || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
5991                                               &readbytes))
5992                     || !TEST_size_t_eq(readbytes, sizeof(msg))
5993                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
5994                 goto end;
5995         }
5996     }
5997
5998     /* Writing on the client after sending close_notify shouldn't be possible */
5999     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
6000         goto end;
6001
6002     if (tst < 4) {
6003         /*
6004          * For these tests the client has sent close_notify but it has not yet
6005          * been received by the server. The server has not sent close_notify
6006          * yet.
6007          */
6008         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
6009                    /*
6010                     * Writing on the server after sending close_notify shouldn't
6011                     * be possible.
6012                     */
6013                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
6014                 || !TEST_int_eq(SSL_shutdown(clientssl), 1)
6015                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6016                 || !TEST_true(SSL_SESSION_is_resumable(sess))
6017                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
6018             goto end;
6019     } else if (tst == 4 || tst == 5) {
6020         /*
6021          * In this test the client has sent close_notify and it has been
6022          * received by the server which has responded with a close_notify. The
6023          * client needs to read the close_notify sent by the server.
6024          */
6025         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
6026                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6027                 || !TEST_true(SSL_SESSION_is_resumable(sess)))
6028             goto end;
6029     } else {
6030         /*
6031          * tst == 6
6032          *
6033          * The client has sent close_notify and is expecting a close_notify
6034          * back, but instead there is application data first. The shutdown
6035          * should fail with a fatal error.
6036          */
6037         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
6038                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
6039             goto end;
6040     }
6041
6042     testresult = 1;
6043
6044  end:
6045     SSL_free(serverssl);
6046     SSL_free(clientssl);
6047     SSL_CTX_free(sctx);
6048     SSL_CTX_free(cctx);
6049
6050     return testresult;
6051 }
6052
6053 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OPENSSL_NO_TLS1_3)
6054 static int cert_cb_cnt;
6055
6056 static int cert_cb(SSL *s, void *arg)
6057 {
6058     SSL_CTX *ctx = (SSL_CTX *)arg;
6059     BIO *in = NULL;
6060     EVP_PKEY *pkey = NULL;
6061     X509 *x509 = NULL, *rootx = NULL;
6062     STACK_OF(X509) *chain = NULL;
6063     char *rootfile = NULL, *ecdsacert = NULL, *ecdsakey = NULL;
6064     int ret = 0;
6065
6066     if (cert_cb_cnt == 0) {
6067         /* Suspend the handshake */
6068         cert_cb_cnt++;
6069         return -1;
6070     } else if (cert_cb_cnt == 1) {
6071         /*
6072          * Update the SSL_CTX, set the certificate and private key and then
6073          * continue the handshake normally.
6074          */
6075         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
6076             return 0;
6077
6078         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
6079                 || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
6080                                                       SSL_FILETYPE_PEM))
6081                 || !TEST_true(SSL_check_private_key(s)))
6082             return 0;
6083         cert_cb_cnt++;
6084         return 1;
6085     } else if (cert_cb_cnt == 3) {
6086         int rv;
6087
6088         rootfile = test_mk_file_path(certsdir, "rootcert.pem");
6089         ecdsacert = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
6090         ecdsakey = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
6091         if (!TEST_ptr(rootfile) || !TEST_ptr(ecdsacert) || !TEST_ptr(ecdsakey))
6092             goto out;
6093         chain = sk_X509_new_null();
6094         if (!TEST_ptr(chain))
6095             goto out;
6096         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6097                 || !TEST_int_ge(BIO_read_filename(in, rootfile), 0)
6098                 || !TEST_ptr(rootx = PEM_read_bio_X509(in, NULL, NULL, NULL))
6099                 || !TEST_true(sk_X509_push(chain, rootx)))
6100             goto out;
6101         rootx = NULL;
6102         BIO_free(in);
6103         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6104                 || !TEST_int_ge(BIO_read_filename(in, ecdsacert), 0)
6105                 || !TEST_ptr(x509 = PEM_read_bio_X509(in, NULL, NULL, NULL)))
6106             goto out;
6107         BIO_free(in);
6108         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6109                 || !TEST_int_ge(BIO_read_filename(in, ecdsakey), 0)
6110                 || !TEST_ptr(pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL)))
6111             goto out;
6112         rv = SSL_check_chain(s, x509, pkey, chain);
6113         /*
6114          * If the cert doesn't show as valid here (e.g., because we don't
6115          * have any shared sigalgs), then we will not set it, and there will
6116          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
6117          * will cause tls_choose_sigalgs() to fail the connection.
6118          */
6119         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
6120                 == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
6121             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
6122                 goto out;
6123         }
6124
6125         ret = 1;
6126     }
6127
6128     /* Abort the handshake */
6129  out:
6130     OPENSSL_free(ecdsacert);
6131     OPENSSL_free(ecdsakey);
6132     OPENSSL_free(rootfile);
6133     BIO_free(in);
6134     EVP_PKEY_free(pkey);
6135     X509_free(x509);
6136     X509_free(rootx);
6137     sk_X509_pop_free(chain, X509_free);
6138     return ret;
6139 }
6140
6141 /*
6142  * Test the certificate callback.
6143  * Test 0: Callback fails
6144  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
6145  * Test 2: Success - SSL_set_SSL_CTX() in the callback
6146  * Test 3: Success - Call SSL_check_chain from the callback
6147  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
6148  *                   chain
6149  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
6150  */
6151 static int test_cert_cb_int(int prot, int tst)
6152 {
6153     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
6154     SSL *clientssl = NULL, *serverssl = NULL;
6155     int testresult = 0, ret;
6156
6157 #ifdef OPENSSL_NO_EC
6158     /* We use an EC cert in these tests, so we skip in a no-ec build */
6159     if (tst >= 3)
6160         return 1;
6161 #endif
6162
6163     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6164                                        TLS_client_method(),
6165                                        TLS1_VERSION,
6166                                        prot,
6167                                        &sctx, &cctx, NULL, NULL)))
6168         goto end;
6169
6170     if (tst == 0)
6171         cert_cb_cnt = -1;
6172     else if (tst >= 3)
6173         cert_cb_cnt = 3;
6174     else
6175         cert_cb_cnt = 0;
6176
6177     if (tst == 2)
6178         snictx = SSL_CTX_new(TLS_server_method());
6179     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
6180
6181     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6182                                       NULL, NULL)))
6183         goto end;
6184
6185     if (tst == 4) {
6186         /*
6187          * We cause SSL_check_chain() to fail by specifying sig_algs that
6188          * the chain doesn't meet (the root uses an RSA cert)
6189          */
6190         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
6191                                              "ecdsa_secp256r1_sha256")))
6192             goto end;
6193     } else if (tst == 5) {
6194         /*
6195          * We cause SSL_check_chain() to fail by specifying sig_algs that
6196          * the ee cert doesn't meet (the ee uses an ECDSA cert)
6197          */
6198         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
6199                            "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
6200             goto end;
6201     }
6202
6203     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
6204     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
6205             || (tst > 0
6206                 && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
6207         goto end;
6208     }
6209
6210     testresult = 1;
6211
6212  end:
6213     SSL_free(serverssl);
6214     SSL_free(clientssl);
6215     SSL_CTX_free(sctx);
6216     SSL_CTX_free(cctx);
6217     SSL_CTX_free(snictx);
6218
6219     return testresult;
6220 }
6221 #endif
6222
6223 static int test_cert_cb(int tst)
6224 {
6225     int testresult = 1;
6226
6227 #ifndef OPENSSL_NO_TLS1_2
6228     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
6229 #endif
6230 #ifndef OPENSSL_NO_TLS1_3
6231     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
6232 #endif
6233
6234     return testresult;
6235 }
6236
6237 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
6238 {
6239     X509 *xcert, *peer;
6240     EVP_PKEY *privpkey;
6241     BIO *in = NULL;
6242
6243     /* Check that SSL_get_peer_certificate() returns something sensible */
6244     peer = SSL_get_peer_certificate(ssl);
6245     if (!TEST_ptr(peer))
6246         return 0;
6247     X509_free(peer);
6248
6249     in = BIO_new_file(cert, "r");
6250     if (!TEST_ptr(in))
6251         return 0;
6252
6253     xcert = PEM_read_bio_X509(in, NULL, NULL, NULL);
6254     BIO_free(in);
6255     if (!TEST_ptr(xcert))
6256         return 0;
6257
6258     in = BIO_new_file(privkey, "r");
6259     if (!TEST_ptr(in)) {
6260         X509_free(xcert);
6261         return 0;
6262     }
6263
6264     privpkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
6265     BIO_free(in);
6266     if (!TEST_ptr(privpkey)) {
6267         X509_free(xcert);
6268         return 0;
6269     }
6270
6271     *x509 = xcert;
6272     *pkey = privpkey;
6273
6274     return 1;
6275 }
6276
6277 static int test_client_cert_cb(int tst)
6278 {
6279     SSL_CTX *cctx = NULL, *sctx = NULL;
6280     SSL *clientssl = NULL, *serverssl = NULL;
6281     int testresult = 0;
6282
6283 #ifdef OPENSSL_NO_TLS1_2
6284     if (tst == 0)
6285         return 1;
6286 #endif
6287 #ifdef OPENSSL_NO_TLS1_3
6288     if (tst == 1)
6289         return 1;
6290 #endif
6291
6292     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6293                                        TLS_client_method(),
6294                                        TLS1_VERSION,
6295                                        tst == 0 ? TLS1_2_VERSION
6296                                                 : TLS1_3_VERSION,
6297                                        &sctx, &cctx, cert, privkey)))
6298         goto end;
6299
6300     /*
6301      * Test that setting a client_cert_cb results in a client certificate being
6302      * sent.
6303      */
6304     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
6305     SSL_CTX_set_verify(sctx,
6306                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
6307                        verify_cb);
6308
6309     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6310                                       NULL, NULL))
6311             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6312                                                 SSL_ERROR_NONE)))
6313         goto end;
6314
6315     testresult = 1;
6316
6317  end:
6318     SSL_free(serverssl);
6319     SSL_free(clientssl);
6320     SSL_CTX_free(sctx);
6321     SSL_CTX_free(cctx);
6322
6323     return testresult;
6324 }
6325
6326 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OPENSSL_NO_TLS1_3)
6327 /*
6328  * Test setting certificate authorities on both client and server.
6329  *
6330  * Test 0: SSL_CTX_set0_CA_list() only
6331  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
6332  * Test 2: Only SSL_CTX_set_client_CA_list()
6333  */
6334 static int test_ca_names_int(int prot, int tst)
6335 {
6336     SSL_CTX *cctx = NULL, *sctx = NULL;
6337     SSL *clientssl = NULL, *serverssl = NULL;
6338     int testresult = 0;
6339     size_t i;
6340     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
6341     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
6342     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
6343     const STACK_OF(X509_NAME) *sktmp = NULL;
6344
6345     for (i = 0; i < OSSL_NELEM(name); i++) {
6346         name[i] = X509_NAME_new();
6347         if (!TEST_ptr(name[i])
6348                 || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
6349                                                          MBSTRING_ASC,
6350                                                          (unsigned char *)
6351                                                          strnames[i],
6352                                                          -1, -1, 0)))
6353             goto end;
6354     }
6355
6356     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6357                                        TLS_client_method(),
6358                                        TLS1_VERSION,
6359                                        prot,
6360                                        &sctx, &cctx, cert, privkey)))
6361         goto end;
6362
6363     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
6364
6365     if (tst == 0 || tst == 1) {
6366         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
6367                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
6368                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
6369                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
6370                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
6371                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
6372             goto end;
6373
6374         SSL_CTX_set0_CA_list(sctx, sk1);
6375         SSL_CTX_set0_CA_list(cctx, sk2);
6376         sk1 = sk2 = NULL;
6377     }
6378     if (tst == 1 || tst == 2) {
6379         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
6380                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
6381                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
6382                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
6383                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
6384                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
6385             goto end;
6386
6387         SSL_CTX_set_client_CA_list(sctx, sk1);
6388         SSL_CTX_set_client_CA_list(cctx, sk2);
6389         sk1 = sk2 = NULL;
6390     }
6391
6392     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6393                                       NULL, NULL))
6394             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6395                                                 SSL_ERROR_NONE)))
6396         goto end;
6397
6398     /*
6399      * We only expect certificate authorities to have been sent to the server
6400      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
6401      */
6402     sktmp = SSL_get0_peer_CA_list(serverssl);
6403     if (prot == TLS1_3_VERSION
6404             && (tst == 0 || tst == 1)) {
6405         if (!TEST_ptr(sktmp)
6406                 || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
6407                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
6408                                               name[0]), 0)
6409                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
6410                                               name[1]), 0))
6411             goto end;
6412     } else if (!TEST_ptr_null(sktmp)) {
6413         goto end;
6414     }
6415
6416     /*
6417      * In all tests we expect certificate authorities to have been sent to the
6418      * client. However, SSL_set_client_CA_list() should override
6419      * SSL_set0_CA_list()
6420      */
6421     sktmp = SSL_get0_peer_CA_list(clientssl);
6422     if (!TEST_ptr(sktmp)
6423             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
6424             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
6425                                           name[tst == 0 ? 0 : 2]), 0)
6426             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
6427                                           name[tst == 0 ? 1 : 3]), 0))
6428         goto end;
6429
6430     testresult = 1;
6431
6432  end:
6433     SSL_free(serverssl);
6434     SSL_free(clientssl);
6435     SSL_CTX_free(sctx);
6436     SSL_CTX_free(cctx);
6437     for (i = 0; i < OSSL_NELEM(name); i++)
6438         X509_NAME_free(name[i]);
6439     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
6440     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
6441
6442     return testresult;
6443 }
6444 #endif
6445
6446 static int test_ca_names(int tst)
6447 {
6448     int testresult = 1;
6449
6450 #ifndef OPENSSL_NO_TLS1_2
6451     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
6452 #endif
6453 #ifndef OPENSSL_NO_TLS1_3
6454     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
6455 #endif
6456
6457     return testresult;
6458 }
6459
6460 /*
6461  * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
6462  * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
6463  * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
6464  * Test 3: Client does not set servername on initial handshake (TLSv1.2)
6465  * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
6466  * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
6467  * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
6468  * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
6469  * Test 8: Client does not set servername on initial handshake(TLSv1.3)
6470  * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
6471  */
6472 static int test_servername(int tst)
6473 {
6474     SSL_CTX *cctx = NULL, *sctx = NULL;
6475     SSL *clientssl = NULL, *serverssl = NULL;
6476     int testresult = 0;
6477     SSL_SESSION *sess = NULL;
6478     const char *sexpectedhost = NULL, *cexpectedhost = NULL;
6479
6480 #ifdef OPENSSL_NO_TLS1_2
6481     if (tst <= 4)
6482         return 1;
6483 #endif
6484 #ifdef OPENSSL_NO_TLS1_3
6485     if (tst >= 5)
6486         return 1;
6487 #endif
6488
6489     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6490                                        TLS_client_method(),
6491                                        TLS1_VERSION,
6492                                        (tst <= 4) ? TLS1_2_VERSION
6493                                                   : TLS1_3_VERSION,
6494                                        &sctx, &cctx, cert, privkey))
6495             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6496                                              NULL, NULL)))
6497         goto end;
6498
6499     if (tst != 1 && tst != 6) {
6500         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
6501                                                               hostname_cb)))
6502             goto end;
6503     }
6504
6505     if (tst != 3 && tst != 8) {
6506         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
6507             goto end;
6508         sexpectedhost = cexpectedhost = "goodhost";
6509     }
6510
6511     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
6512         goto end;
6513
6514     if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
6515                      cexpectedhost)
6516             || !TEST_str_eq(SSL_get_servername(serverssl,
6517                                                TLSEXT_NAMETYPE_host_name),
6518                             sexpectedhost))
6519         goto end;
6520
6521     /* Now repeat with a resumption handshake */
6522
6523     if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
6524             || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
6525             || !TEST_true(SSL_SESSION_is_resumable(sess))
6526             || !TEST_int_eq(SSL_shutdown(serverssl), 0))
6527         goto end;
6528
6529     SSL_free(clientssl);
6530     SSL_free(serverssl);
6531     clientssl = serverssl = NULL;
6532
6533     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6534                                       NULL)))
6535         goto end;
6536
6537     if (!TEST_true(SSL_set_session(clientssl, sess)))
6538         goto end;
6539
6540     sexpectedhost = cexpectedhost = "goodhost";
6541     if (tst == 2 || tst == 7) {
6542         /* Set an inconsistent hostname */
6543         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
6544             goto end;
6545         /*
6546          * In TLSv1.2 we expect the hostname from the original handshake, in
6547          * TLSv1.3 we expect the hostname from this handshake
6548          */
6549         if (tst == 7)
6550             sexpectedhost = cexpectedhost = "altgoodhost";
6551
6552         if (!TEST_str_eq(SSL_get_servername(clientssl,
6553                                             TLSEXT_NAMETYPE_host_name),
6554                          "altgoodhost"))
6555             goto end;
6556     } else if (tst == 4 || tst == 9) {
6557         /*
6558          * A TLSv1.3 session does not associate a session with a servername,
6559          * but a TLSv1.2 session does.
6560          */
6561         if (tst == 9)
6562             sexpectedhost = cexpectedhost = NULL;
6563
6564         if (!TEST_str_eq(SSL_get_servername(clientssl,
6565                                             TLSEXT_NAMETYPE_host_name),
6566                          cexpectedhost))
6567             goto end;
6568     } else {
6569         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
6570             goto end;
6571         /*
6572          * In a TLSv1.2 resumption where the hostname was not acknowledged
6573          * we expect the hostname on the server to be empty. On the client we
6574          * return what was requested in this case.
6575          *
6576          * Similarly if the client didn't set a hostname on an original TLSv1.2
6577          * session but is now, the server hostname will be empty, but the client
6578          * is as we set it.
6579          */
6580         if (tst == 1 || tst == 3)
6581             sexpectedhost = NULL;
6582
6583         if (!TEST_str_eq(SSL_get_servername(clientssl,
6584                                             TLSEXT_NAMETYPE_host_name),
6585                          "goodhost"))
6586             goto end;
6587     }
6588
6589     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
6590         goto end;
6591
6592     if (!TEST_true(SSL_session_reused(clientssl))
6593             || !TEST_true(SSL_session_reused(serverssl))
6594             || !TEST_str_eq(SSL_get_servername(clientssl,
6595                                                TLSEXT_NAMETYPE_host_name),
6596                             cexpectedhost)
6597             || !TEST_str_eq(SSL_get_servername(serverssl,
6598                                                TLSEXT_NAMETYPE_host_name),
6599                             sexpectedhost))
6600         goto end;
6601
6602     testresult = 1;
6603
6604  end:
6605     SSL_SESSION_free(sess);
6606     SSL_free(serverssl);
6607     SSL_free(clientssl);
6608     SSL_CTX_free(sctx);
6609     SSL_CTX_free(cctx);
6610
6611     return testresult;
6612 }
6613
6614 #ifndef OPENSSL_NO_TLS1_2
6615 static int test_ssl_dup(void)
6616 {
6617     SSL_CTX *cctx = NULL, *sctx = NULL;
6618     SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL;
6619     int testresult = 0;
6620     BIO *rbio = NULL, *wbio = NULL;
6621
6622     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6623                                        TLS_client_method(),
6624                                        0,
6625                                        0,
6626                                        &sctx, &cctx, cert, privkey)))
6627         goto end;
6628
6629     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6630                                              NULL, NULL)))
6631         goto end;
6632
6633     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
6634             || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION)))
6635         goto end;
6636
6637     client2ssl = SSL_dup(clientssl);
6638     rbio = SSL_get_rbio(clientssl);
6639     if (!TEST_ptr(rbio)
6640             || !TEST_true(BIO_up_ref(rbio)))
6641         goto end;
6642     SSL_set0_rbio(client2ssl, rbio);
6643     rbio = NULL;
6644
6645     wbio = SSL_get_wbio(clientssl);
6646     if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio)))
6647         goto end;
6648     SSL_set0_wbio(client2ssl, wbio);
6649     rbio = NULL;
6650
6651     if (!TEST_ptr(client2ssl)
6652                /* Handshake not started so pointers should be different */
6653             || !TEST_ptr_ne(clientssl, client2ssl))
6654         goto end;
6655
6656     if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION)
6657             || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION))
6658         goto end;
6659
6660     if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE)))
6661         goto end;
6662
6663     SSL_free(clientssl);
6664     clientssl = SSL_dup(client2ssl);
6665     if (!TEST_ptr(clientssl)
6666                /* Handshake has finished so pointers should be the same */
6667             || !TEST_ptr_eq(clientssl, client2ssl))
6668         goto end;
6669
6670     testresult = 1;
6671
6672  end:
6673     SSL_free(serverssl);
6674     SSL_free(clientssl);
6675     SSL_free(client2ssl);
6676     SSL_CTX_free(sctx);
6677     SSL_CTX_free(cctx);
6678
6679     return testresult;
6680 }
6681 #endif
6682
6683 #ifndef OPENSSL_NO_TLS1_3
6684 /*
6685  * Test that setting an SNI callback works with TLSv1.3. Specifically we check
6686  * that it works even without a certificate configured for the original
6687  * SSL_CTX
6688  */
6689 static int test_sni_tls13(void)
6690 {
6691     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6692     SSL *clientssl = NULL, *serverssl = NULL;
6693     int testresult = 0;
6694
6695     /* Reset callback counter */
6696     snicb = 0;
6697
6698     /* Create an initial SSL_CTX with no certificate configured */
6699     sctx = SSL_CTX_new(TLS_server_method());
6700     if (!TEST_ptr(sctx))
6701         goto end;
6702     /* Require TLSv1.3 as a minimum */
6703     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
6704                                        TLS1_3_VERSION, 0, &sctx2, &cctx, cert,
6705                                        privkey)))
6706         goto end;
6707
6708     /* Set up SNI */
6709     if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
6710             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
6711         goto end;
6712
6713     /*
6714      * Connection should still succeed because the final SSL_CTX has the right
6715      * certificates configured.
6716      */
6717     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6718                                       &clientssl, NULL, NULL))
6719             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6720                                                 SSL_ERROR_NONE)))
6721         goto end;
6722
6723     /* We should have had the SNI callback called exactly once */
6724     if (!TEST_int_eq(snicb, 1))
6725         goto end;
6726
6727     testresult = 1;
6728
6729 end:
6730     SSL_free(serverssl);
6731     SSL_free(clientssl);
6732     SSL_CTX_free(sctx2);
6733     SSL_CTX_free(sctx);
6734     SSL_CTX_free(cctx);
6735     return testresult;
6736 }
6737
6738 /*
6739  * Test that the lifetime hint of a TLSv1.3 ticket is no more than 1 week
6740  * 0 = TLSv1.2
6741  * 1 = TLSv1.3
6742  */
6743 static int test_ticket_lifetime(int idx)
6744 {
6745     SSL_CTX *cctx = NULL, *sctx = NULL;
6746     SSL *clientssl = NULL, *serverssl = NULL;
6747     int testresult = 0;
6748     int version = TLS1_3_VERSION;
6749
6750 #define ONE_WEEK_SEC (7 * 24 * 60 * 60)
6751 #define TWO_WEEK_SEC (2 * ONE_WEEK_SEC)
6752
6753     if (idx == 0) {
6754 #ifdef OPENSSL_NO_TLS1_2
6755         TEST_info("Skipping: TLS 1.2 is disabled.");
6756         return 1;
6757 #else
6758         version = TLS1_2_VERSION;
6759 #endif
6760     }
6761
6762     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6763                                        TLS_client_method(), version, version,
6764                                        &sctx, &cctx, cert, privkey)))
6765         goto end;
6766
6767     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6768                                       &clientssl, NULL, NULL)))
6769         goto end;
6770
6771     /*
6772      * Set the timeout to be more than 1 week
6773      * make sure the returned value is the default
6774      */
6775     if (!TEST_long_eq(SSL_CTX_set_timeout(sctx, TWO_WEEK_SEC),
6776                       SSL_get_default_timeout(serverssl)))
6777         goto end;
6778
6779     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
6780         goto end;
6781
6782     if (idx == 0) {
6783         /* TLSv1.2 uses the set value */
6784         if (!TEST_ulong_eq(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), TWO_WEEK_SEC))
6785             goto end;
6786     } else {
6787         /* TLSv1.3 uses the limited value */
6788         if (!TEST_ulong_le(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), ONE_WEEK_SEC))
6789             goto end;
6790     }
6791     testresult = 1;
6792
6793 end:
6794     SSL_free(serverssl);
6795     SSL_free(clientssl);
6796     SSL_CTX_free(sctx);
6797     SSL_CTX_free(cctx);
6798     return testresult;
6799 }
6800 #endif
6801 /*
6802  * Test that setting an ALPN does not violate RFC
6803  */
6804 static int test_set_alpn(void)
6805 {
6806     SSL_CTX *ctx = NULL;
6807     SSL *ssl = NULL;
6808     int testresult = 0;
6809
6810     unsigned char bad0[] = { 0x00, 'b', 'a', 'd' };
6811     unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' };
6812     unsigned char bad1[] = { 0x01, 'b', 'a', 'd' };
6813     unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00};
6814     unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd'};
6815     unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd'};
6816
6817     /* Create an initial SSL_CTX with no certificate configured */
6818     ctx = SSL_CTX_new(TLS_server_method());
6819     if (!TEST_ptr(ctx))
6820         goto end;
6821
6822     /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */
6823     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2)))
6824         goto end;
6825     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0)))
6826         goto end;
6827     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good))))
6828         goto end;
6829     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1)))
6830         goto end;
6831     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0))))
6832         goto end;
6833     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1))))
6834         goto end;
6835     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2))))
6836         goto end;
6837     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3))))
6838         goto end;
6839     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4))))
6840         goto end;
6841
6842     ssl = SSL_new(ctx);
6843     if (!TEST_ptr(ssl))
6844         goto end;
6845
6846     if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2)))
6847         goto end;
6848     if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0)))
6849         goto end;
6850     if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good))))
6851         goto end;
6852     if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1)))
6853         goto end;
6854     if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0))))
6855         goto end;
6856     if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1))))
6857         goto end;
6858     if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2))))
6859         goto end;
6860     if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3))))
6861         goto end;
6862     if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4))))
6863         goto end;
6864
6865     testresult = 1;
6866
6867 end:
6868     SSL_free(ssl);
6869     SSL_CTX_free(ctx);
6870     return testresult;
6871 }
6872
6873 /*
6874  * Test SSL_CTX_set1_verify/chain_cert_store and SSL_CTX_get_verify/chain_cert_store.
6875  */
6876 static int test_set_verify_cert_store_ssl_ctx(void)
6877 {
6878    SSL_CTX *ctx = NULL;
6879    int testresult = 0;
6880    X509_STORE *store = NULL, *new_store = NULL,
6881               *cstore = NULL, *new_cstore = NULL;
6882
6883    /* Create an initial SSL_CTX. */
6884    ctx = SSL_CTX_new(TLS_server_method());
6885    if (!TEST_ptr(ctx))
6886        goto end;
6887
6888    /* Retrieve verify store pointer. */
6889    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
6890        goto end;
6891
6892    /* Retrieve chain store pointer. */
6893    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
6894        goto end;
6895
6896    /* We haven't set any yet, so this should be NULL. */
6897    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
6898        goto end;
6899
6900    /* Create stores. We use separate stores so pointers are different. */
6901    new_store = X509_STORE_new();
6902    if (!TEST_ptr(new_store))
6903        goto end;
6904
6905    new_cstore = X509_STORE_new();
6906    if (!TEST_ptr(new_cstore))
6907        goto end;
6908
6909    /* Set stores. */
6910    if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, new_store)))
6911        goto end;
6912
6913    if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, new_cstore)))
6914        goto end;
6915
6916    /* Should be able to retrieve the same pointer. */
6917    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
6918        goto end;
6919
6920    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
6921        goto end;
6922
6923    if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
6924        goto end;
6925
6926    /* Should be able to unset again. */
6927    if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, NULL)))
6928        goto end;
6929
6930    if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, NULL)))
6931        goto end;
6932
6933    /* Should now be NULL. */
6934    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
6935        goto end;
6936
6937    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
6938        goto end;
6939
6940    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
6941        goto end;
6942
6943    testresult = 1;
6944
6945 end:
6946    X509_STORE_free(new_store);
6947    X509_STORE_free(new_cstore);
6948    SSL_CTX_free(ctx);
6949    return testresult;
6950 }
6951
6952 /*
6953  * Test SSL_set1_verify/chain_cert_store and SSL_get_verify/chain_cert_store.
6954  */
6955 static int test_set_verify_cert_store_ssl(void)
6956 {
6957    SSL_CTX *ctx = NULL;
6958    SSL *ssl = NULL;
6959    int testresult = 0;
6960    X509_STORE *store = NULL, *new_store = NULL,
6961               *cstore = NULL, *new_cstore = NULL;
6962
6963    /* Create an initial SSL_CTX. */
6964    ctx = SSL_CTX_new(TLS_server_method());
6965    if (!TEST_ptr(ctx))
6966        goto end;
6967
6968    /* Create an SSL object. */
6969    ssl = SSL_new(ctx);
6970    if (!TEST_ptr(ssl))
6971        goto end;
6972
6973    /* Retrieve verify store pointer. */
6974    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
6975        goto end;
6976
6977    /* Retrieve chain store pointer. */
6978    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
6979        goto end;
6980
6981    /* We haven't set any yet, so this should be NULL. */
6982    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
6983        goto end;
6984
6985    /* Create stores. We use separate stores so pointers are different. */
6986    new_store = X509_STORE_new();
6987    if (!TEST_ptr(new_store))
6988        goto end;
6989
6990    new_cstore = X509_STORE_new();
6991    if (!TEST_ptr(new_cstore))
6992        goto end;
6993
6994    /* Set stores. */
6995    if (!TEST_true(SSL_set1_verify_cert_store(ssl, new_store)))
6996        goto end;
6997
6998    if (!TEST_true(SSL_set1_chain_cert_store(ssl, new_cstore)))
6999        goto end;
7000
7001    /* Should be able to retrieve the same pointer. */
7002    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
7003        goto end;
7004
7005    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
7006        goto end;
7007
7008    if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
7009        goto end;
7010
7011    /* Should be able to unset again. */
7012    if (!TEST_true(SSL_set1_verify_cert_store(ssl, NULL)))
7013        goto end;
7014
7015    if (!TEST_true(SSL_set1_chain_cert_store(ssl, NULL)))
7016        goto end;
7017
7018    /* Should now be NULL. */
7019    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
7020        goto end;
7021
7022    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
7023        goto end;
7024
7025    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
7026        goto end;
7027
7028    testresult = 1;
7029
7030 end:
7031    X509_STORE_free(new_store);
7032    X509_STORE_free(new_cstore);
7033    SSL_free(ssl);
7034    SSL_CTX_free(ctx);
7035    return testresult;
7036 }
7037
7038 static int test_inherit_verify_param(void)
7039 {
7040     int testresult = 0;
7041
7042     SSL_CTX *ctx = NULL;
7043     X509_VERIFY_PARAM *cp = NULL;
7044     SSL *ssl = NULL;
7045     X509_VERIFY_PARAM *sp = NULL;
7046     int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
7047
7048     ctx = SSL_CTX_new(TLS_server_method());
7049     if (!TEST_ptr(ctx))
7050         goto end;
7051
7052     cp = SSL_CTX_get0_param(ctx);
7053     if (!TEST_ptr(cp))
7054         goto end;
7055     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0))
7056         goto end;
7057
7058     X509_VERIFY_PARAM_set_hostflags(cp, hostflags);
7059
7060     ssl = SSL_new(ctx);
7061     if (!TEST_ptr(ssl))
7062         goto end;
7063
7064     sp = SSL_get0_param(ssl);
7065     if (!TEST_ptr(sp))
7066         goto end;
7067     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags))
7068         goto end;
7069
7070     testresult = 1;
7071
7072  end:
7073     SSL_free(ssl);
7074     SSL_CTX_free(ctx);
7075
7076     return testresult;
7077 }
7078
7079 int setup_tests(void)
7080 {
7081     if (!TEST_ptr(certsdir = test_get_argument(0))
7082             || !TEST_ptr(srpvfile = test_get_argument(1))
7083             || !TEST_ptr(tmpfilename = test_get_argument(2)))
7084         return 0;
7085
7086     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
7087 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
7088         TEST_error("not supported in this build");
7089         return 0;
7090 #else
7091         int i, mcount, rcount, fcount;
7092
7093         for (i = 0; i < 4; i++)
7094             test_export_key_mat(i);
7095         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
7096         test_printf_stdout("malloc %d realloc %d free %d\n",
7097                 mcount, rcount, fcount);
7098         return 1;
7099 #endif
7100     }
7101
7102     cert = test_mk_file_path(certsdir, "servercert.pem");
7103     if (cert == NULL)
7104         return 0;
7105
7106     privkey = test_mk_file_path(certsdir, "serverkey.pem");
7107     if (privkey == NULL) {
7108         OPENSSL_free(cert);
7109         return 0;
7110     }
7111
7112     ADD_TEST(test_large_message_tls);
7113     ADD_TEST(test_large_message_tls_read_ahead);
7114 #ifndef OPENSSL_NO_DTLS
7115     ADD_TEST(test_large_message_dtls);
7116 #endif
7117 #ifndef OPENSSL_NO_OCSP
7118     ADD_TEST(test_tlsext_status_type);
7119 #endif
7120     ADD_TEST(test_session_with_only_int_cache);
7121     ADD_TEST(test_session_with_only_ext_cache);
7122     ADD_TEST(test_session_with_both_cache);
7123 #ifndef OPENSSL_NO_TLS1_3
7124     ADD_ALL_TESTS(test_stateful_tickets, 3);
7125     ADD_ALL_TESTS(test_stateless_tickets, 3);
7126     ADD_TEST(test_psk_tickets);
7127 #endif
7128     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
7129     ADD_TEST(test_ssl_bio_pop_next_bio);
7130     ADD_TEST(test_ssl_bio_pop_ssl_bio);
7131     ADD_TEST(test_ssl_bio_change_rbio);
7132     ADD_TEST(test_ssl_bio_change_wbio);
7133 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
7134     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
7135     ADD_TEST(test_keylog);
7136 #endif
7137 #ifndef OPENSSL_NO_TLS1_3
7138     ADD_TEST(test_keylog_no_master_key);
7139 #endif
7140 #ifndef OPENSSL_NO_TLS1_2
7141     ADD_TEST(test_client_hello_cb);
7142     ADD_TEST(test_ccs_change_cipher);
7143 #endif
7144 #ifndef OPENSSL_NO_TLS1_3
7145     ADD_ALL_TESTS(test_early_data_read_write, 3);
7146     /*
7147      * We don't do replay tests for external PSK. Replay protection isn't used
7148      * in that scenario.
7149      */
7150     ADD_ALL_TESTS(test_early_data_replay, 2);
7151     ADD_ALL_TESTS(test_early_data_skip, 3);
7152     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
7153     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, 3);
7154     ADD_ALL_TESTS(test_early_data_skip_abort, 3);
7155     ADD_ALL_TESTS(test_early_data_not_sent, 3);
7156     ADD_ALL_TESTS(test_early_data_psk, 8);
7157     ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 5);
7158     ADD_ALL_TESTS(test_early_data_not_expected, 3);
7159 # ifndef OPENSSL_NO_TLS1_2
7160     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
7161 # endif
7162 #endif
7163 #ifndef OPENSSL_NO_TLS1_3
7164     ADD_ALL_TESTS(test_set_ciphersuite, 10);
7165     ADD_TEST(test_ciphersuite_change);
7166     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
7167 #ifdef OPENSSL_NO_PSK
7168     ADD_ALL_TESTS(test_tls13_psk, 1);
7169 #else
7170     ADD_ALL_TESTS(test_tls13_psk, 4);
7171 #endif  /* OPENSSL_NO_PSK */
7172     ADD_ALL_TESTS(test_custom_exts, 6);
7173     ADD_TEST(test_stateless);
7174     ADD_TEST(test_pha_key_update);
7175 #else
7176     ADD_ALL_TESTS(test_custom_exts, 3);
7177 #endif
7178     ADD_ALL_TESTS(test_serverinfo, 8);
7179     ADD_ALL_TESTS(test_export_key_mat, 6);
7180 #ifndef OPENSSL_NO_TLS1_3
7181     ADD_ALL_TESTS(test_export_key_mat_early, 3);
7182     ADD_TEST(test_key_update);
7183     ADD_ALL_TESTS(test_key_update_in_write, 2);
7184 #endif
7185     ADD_ALL_TESTS(test_ssl_clear, 2);
7186     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
7187 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
7188     ADD_ALL_TESTS(test_srp, 6);
7189 #endif
7190     ADD_ALL_TESTS(test_info_callback, 6);
7191     ADD_ALL_TESTS(test_ssl_pending, 2);
7192     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
7193     ADD_ALL_TESTS(test_ticket_callbacks, 12);
7194     ADD_ALL_TESTS(test_shutdown, 7);
7195     ADD_ALL_TESTS(test_cert_cb, 6);
7196     ADD_ALL_TESTS(test_client_cert_cb, 2);
7197     ADD_ALL_TESTS(test_ca_names, 3);
7198     ADD_ALL_TESTS(test_servername, 10);
7199 #ifndef OPENSSL_NO_TLS1_2
7200     ADD_TEST(test_ssl_dup);
7201 #endif
7202 #ifndef OPENSSL_NO_TLS1_3
7203     ADD_TEST(test_sni_tls13);
7204     ADD_ALL_TESTS(test_ticket_lifetime, 2);
7205 #endif
7206     ADD_TEST(test_set_alpn);
7207     ADD_TEST(test_set_verify_cert_store_ssl_ctx);
7208     ADD_TEST(test_set_verify_cert_store_ssl);
7209     ADD_TEST(test_inherit_verify_param);
7210     return 1;
7211 }
7212
7213 void cleanup_tests(void)
7214 {
7215     OPENSSL_free(cert);
7216     OPENSSL_free(privkey);
7217     bio_s_mempacket_test_free();
7218     bio_s_always_retry_free();
7219 }