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