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