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