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