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