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