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