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