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