TLS: use EVP for HMAC throughout libssl.
[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         return  SSL_TLSEXT_ERR_OK;
3205
3206     return SSL_TLSEXT_ERR_NOACK;
3207 }
3208
3209 static const char *servalpn;
3210
3211 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
3212                           unsigned char *outlen, const unsigned char *in,
3213                           unsigned int inlen, void *arg)
3214 {
3215     unsigned int protlen = 0;
3216     const unsigned char *prot;
3217
3218     for (prot = in; prot < in + inlen; prot += protlen) {
3219         protlen = *prot++;
3220         if (in + inlen < prot + protlen)
3221             return SSL_TLSEXT_ERR_NOACK;
3222
3223         if (protlen == strlen(servalpn)
3224                 && memcmp(prot, servalpn, protlen) == 0) {
3225             *out = prot;
3226             *outlen = protlen;
3227             return SSL_TLSEXT_ERR_OK;
3228         }
3229     }
3230
3231     return SSL_TLSEXT_ERR_NOACK;
3232 }
3233
3234 /* Test that a PSK can be used to send early_data */
3235 static int test_early_data_psk(int idx)
3236 {
3237     SSL_CTX *cctx = NULL, *sctx = NULL;
3238     SSL *clientssl = NULL, *serverssl = NULL;
3239     int testresult = 0;
3240     SSL_SESSION *sess = NULL;
3241     unsigned char alpnlist[] = {
3242         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
3243         'l', 'p', 'n'
3244     };
3245 #define GOODALPNLEN     9
3246 #define BADALPNLEN      8
3247 #define GOODALPN        (alpnlist)
3248 #define BADALPN         (alpnlist + GOODALPNLEN)
3249     int err = 0;
3250     unsigned char buf[20];
3251     size_t readbytes, written;
3252     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
3253     int edstatus = SSL_EARLY_DATA_ACCEPTED;
3254
3255     /* We always set this up with a final parameter of "2" for PSK */
3256     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3257                                         &serverssl, &sess, 2)))
3258         goto end;
3259
3260     servalpn = "goodalpn";
3261
3262     /*
3263      * Note: There is no test for inconsistent SNI with late client detection.
3264      * This is because servers do not acknowledge SNI even if they are using
3265      * it in a resumption handshake - so it is not actually possible for a
3266      * client to detect a problem.
3267      */
3268     switch (idx) {
3269     case 0:
3270         /* Set inconsistent SNI (early client detection) */
3271         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
3272         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
3273                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
3274             goto end;
3275         break;
3276
3277     case 1:
3278         /* Set inconsistent ALPN (early client detection) */
3279         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
3280         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
3281         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
3282                                                       GOODALPNLEN))
3283                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
3284                                                    BADALPNLEN)))
3285             goto end;
3286         break;
3287
3288     case 2:
3289         /*
3290          * Set invalid protocol version. Technically this affects PSKs without
3291          * early_data too, but we test it here because it is similar to the
3292          * SNI/ALPN consistency tests.
3293          */
3294         err = SSL_R_BAD_PSK;
3295         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
3296             goto end;
3297         break;
3298
3299     case 3:
3300         /*
3301          * Set inconsistent SNI (server detected). In this case the connection
3302          * will succeed but reject early_data.
3303          */
3304         SSL_SESSION_free(serverpsk);
3305         serverpsk = SSL_SESSION_dup(clientpsk);
3306         if (!TEST_ptr(serverpsk)
3307                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
3308             goto end;
3309         edstatus = SSL_EARLY_DATA_REJECTED;
3310         readearlyres = SSL_READ_EARLY_DATA_FINISH;
3311         /* Fall through */
3312     case 4:
3313         /* Set consistent SNI */
3314         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
3315                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
3316                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
3317                                 hostname_cb)))
3318             goto end;
3319         break;
3320
3321     case 5:
3322         /*
3323          * Set inconsistent ALPN (server detected). In this case the connection
3324          * will succeed but reject early_data.
3325          */
3326         servalpn = "badalpn";
3327         edstatus = SSL_EARLY_DATA_REJECTED;
3328         readearlyres = SSL_READ_EARLY_DATA_FINISH;
3329         /* Fall through */
3330     case 6:
3331         /*
3332          * Set consistent ALPN.
3333          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
3334          * accepts a list of protos (each one length prefixed).
3335          * SSL_set1_alpn_selected accepts a single protocol (not length
3336          * prefixed)
3337          */
3338         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
3339                                                       GOODALPNLEN - 1))
3340                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
3341                                                    GOODALPNLEN)))
3342             goto end;
3343
3344         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
3345         break;
3346
3347     case 7:
3348         /* Set inconsistent ALPN (late client detection) */
3349         SSL_SESSION_free(serverpsk);
3350         serverpsk = SSL_SESSION_dup(clientpsk);
3351         if (!TEST_ptr(serverpsk)
3352                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
3353                                                              BADALPN + 1,
3354                                                              BADALPNLEN - 1))
3355                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
3356                                                              GOODALPN + 1,
3357                                                              GOODALPNLEN - 1))
3358                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
3359                                                    sizeof(alpnlist))))
3360             goto end;
3361         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
3362         edstatus = SSL_EARLY_DATA_ACCEPTED;
3363         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
3364         /* SSL_connect() call should fail */
3365         connectres = -1;
3366         break;
3367
3368     default:
3369         TEST_error("Bad test index");
3370         goto end;
3371     }
3372
3373     SSL_set_connect_state(clientssl);
3374     if (err != 0) {
3375         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3376                                             &written))
3377                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
3378                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
3379             goto end;
3380     } else {
3381         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3382                                             &written)))
3383             goto end;
3384
3385         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3386                                              &readbytes), readearlyres)
3387                 || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
3388                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3389                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
3390                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
3391             goto end;
3392     }
3393
3394     testresult = 1;
3395
3396  end:
3397     SSL_SESSION_free(sess);
3398     SSL_SESSION_free(clientpsk);
3399     SSL_SESSION_free(serverpsk);
3400     clientpsk = serverpsk = NULL;
3401     SSL_free(serverssl);
3402     SSL_free(clientssl);
3403     SSL_CTX_free(sctx);
3404     SSL_CTX_free(cctx);
3405     return testresult;
3406 }
3407
3408 /*
3409  * Test that a server that doesn't try to read early data can handle a
3410  * client sending some.
3411  */
3412 static int test_early_data_not_expected(int idx)
3413 {
3414     SSL_CTX *cctx = NULL, *sctx = NULL;
3415     SSL *clientssl = NULL, *serverssl = NULL;
3416     int testresult = 0;
3417     SSL_SESSION *sess = NULL;
3418     unsigned char buf[20];
3419     size_t readbytes, written;
3420
3421     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3422                                         &serverssl, &sess, idx)))
3423         goto end;
3424
3425     /* Write some early data */
3426     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3427                                         &written)))
3428         goto end;
3429
3430     /*
3431      * Server should skip over early data and then block waiting for client to
3432      * continue handshake
3433      */
3434     if (!TEST_int_le(SSL_accept(serverssl), 0)
3435      || !TEST_int_gt(SSL_connect(clientssl), 0)
3436      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3437                      SSL_EARLY_DATA_REJECTED)
3438      || !TEST_int_gt(SSL_accept(serverssl), 0)
3439      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3440                      SSL_EARLY_DATA_REJECTED))
3441         goto end;
3442
3443     /* Send some normal data from client to server */
3444     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
3445             || !TEST_size_t_eq(written, strlen(MSG2)))
3446         goto end;
3447
3448     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3449             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3450         goto end;
3451
3452     testresult = 1;
3453
3454  end:
3455     SSL_SESSION_free(sess);
3456     SSL_SESSION_free(clientpsk);
3457     SSL_SESSION_free(serverpsk);
3458     clientpsk = serverpsk = NULL;
3459     SSL_free(serverssl);
3460     SSL_free(clientssl);
3461     SSL_CTX_free(sctx);
3462     SSL_CTX_free(cctx);
3463     return testresult;
3464 }
3465
3466
3467 # ifndef OPENSSL_NO_TLS1_2
3468 /*
3469  * Test that a server attempting to read early data can handle a connection
3470  * from a TLSv1.2 client.
3471  */
3472 static int test_early_data_tls1_2(int idx)
3473 {
3474     SSL_CTX *cctx = NULL, *sctx = NULL;
3475     SSL *clientssl = NULL, *serverssl = NULL;
3476     int testresult = 0;
3477     unsigned char buf[20];
3478     size_t readbytes, written;
3479
3480     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3481                                         &serverssl, NULL, idx)))
3482         goto end;
3483
3484     /* Write some data - should block due to handshake with server */
3485     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
3486     SSL_set_connect_state(clientssl);
3487     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
3488         goto end;
3489
3490     /*
3491      * Server should do TLSv1.2 handshake. First it will block waiting for more
3492      * messages from client after ServerDone. Then SSL_read_early_data should
3493      * finish and detect that early data has not been sent
3494      */
3495     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3496                                          &readbytes),
3497                      SSL_READ_EARLY_DATA_ERROR))
3498         goto end;
3499
3500     /*
3501      * Continue writing the message we started earlier. Will still block waiting
3502      * for the CCS/Finished from server
3503      */
3504     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
3505             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3506                                                 &readbytes),
3507                             SSL_READ_EARLY_DATA_FINISH)
3508             || !TEST_size_t_eq(readbytes, 0)
3509             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3510                             SSL_EARLY_DATA_NOT_SENT))
3511         goto end;
3512
3513     /* Continue writing the message we started earlier */
3514     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
3515             || !TEST_size_t_eq(written, strlen(MSG1))
3516             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3517                             SSL_EARLY_DATA_NOT_SENT)
3518             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3519             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
3520             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
3521             || !TEST_size_t_eq(written, strlen(MSG2))
3522             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
3523             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3524         goto end;
3525
3526     testresult = 1;
3527
3528  end:
3529     SSL_SESSION_free(clientpsk);
3530     SSL_SESSION_free(serverpsk);
3531     clientpsk = serverpsk = NULL;
3532     SSL_free(serverssl);
3533     SSL_free(clientssl);
3534     SSL_CTX_free(sctx);
3535     SSL_CTX_free(cctx);
3536
3537     return testresult;
3538 }
3539 # endif /* OPENSSL_NO_TLS1_2 */
3540
3541 /*
3542  * Test configuring the TLSv1.3 ciphersuites
3543  *
3544  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
3545  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
3546  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
3547  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
3548  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
3549  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
3550  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
3551  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
3552  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
3553  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
3554  */
3555 static int test_set_ciphersuite(int idx)
3556 {
3557     SSL_CTX *cctx = NULL, *sctx = NULL;
3558     SSL *clientssl = NULL, *serverssl = NULL;
3559     int testresult = 0;
3560
3561     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3562                                        TLS1_VERSION, 0,
3563                                        &sctx, &cctx, cert, privkey))
3564             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
3565                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
3566         goto end;
3567
3568     if (idx >=4 && idx <= 7) {
3569         /* SSL_CTX explicit cipher list */
3570         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
3571             goto end;
3572     }
3573
3574     if (idx == 0 || idx == 4) {
3575         /* Default ciphersuite */
3576         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3577                                                 "TLS_AES_128_GCM_SHA256")))
3578             goto end;
3579     } else if (idx == 1 || idx == 5) {
3580         /* Non default ciphersuite */
3581         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3582                                                 "TLS_AES_128_CCM_SHA256")))
3583             goto end;
3584     }
3585
3586     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3587                                           &clientssl, NULL, NULL)))
3588         goto end;
3589
3590     if (idx == 8 || idx == 9) {
3591         /* SSL explicit cipher list */
3592         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
3593             goto end;
3594     }
3595
3596     if (idx == 2 || idx == 6 || idx == 8) {
3597         /* Default ciphersuite */
3598         if (!TEST_true(SSL_set_ciphersuites(clientssl,
3599                                             "TLS_AES_128_GCM_SHA256")))
3600             goto end;
3601     } else if (idx == 3 || idx == 7 || idx == 9) {
3602         /* Non default ciphersuite */
3603         if (!TEST_true(SSL_set_ciphersuites(clientssl,
3604                                             "TLS_AES_128_CCM_SHA256")))
3605             goto end;
3606     }
3607
3608     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
3609         goto end;
3610
3611     testresult = 1;
3612
3613  end:
3614     SSL_free(serverssl);
3615     SSL_free(clientssl);
3616     SSL_CTX_free(sctx);
3617     SSL_CTX_free(cctx);
3618
3619     return testresult;
3620 }
3621
3622 static int test_ciphersuite_change(void)
3623 {
3624     SSL_CTX *cctx = NULL, *sctx = NULL;
3625     SSL *clientssl = NULL, *serverssl = NULL;
3626     SSL_SESSION *clntsess = NULL;
3627     int testresult = 0;
3628     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
3629
3630     /* Create a session based on SHA-256 */
3631     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3632                                        TLS1_VERSION, 0,
3633                                        &sctx, &cctx, cert, privkey))
3634             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
3635                                                    "TLS_AES_128_GCM_SHA256"))
3636             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3637                                           &clientssl, NULL, NULL))
3638             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3639                                                 SSL_ERROR_NONE)))
3640         goto end;
3641
3642     clntsess = SSL_get1_session(clientssl);
3643     /* Save for later */
3644     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
3645     SSL_shutdown(clientssl);
3646     SSL_shutdown(serverssl);
3647     SSL_free(serverssl);
3648     SSL_free(clientssl);
3649     serverssl = clientssl = NULL;
3650
3651 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3652     /* Check we can resume a session with a different SHA-256 ciphersuite */
3653     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3654                                             "TLS_CHACHA20_POLY1305_SHA256"))
3655             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3656                                              NULL, NULL))
3657             || !TEST_true(SSL_set_session(clientssl, clntsess))
3658             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3659                                                 SSL_ERROR_NONE))
3660             || !TEST_true(SSL_session_reused(clientssl)))
3661         goto end;
3662
3663     SSL_SESSION_free(clntsess);
3664     clntsess = SSL_get1_session(clientssl);
3665     SSL_shutdown(clientssl);
3666     SSL_shutdown(serverssl);
3667     SSL_free(serverssl);
3668     SSL_free(clientssl);
3669     serverssl = clientssl = NULL;
3670 # endif
3671
3672     /*
3673      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
3674      * succeeds but does not resume.
3675      */
3676     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
3677             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3678                                              NULL, NULL))
3679             || !TEST_true(SSL_set_session(clientssl, clntsess))
3680             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3681                                                 SSL_ERROR_SSL))
3682             || !TEST_false(SSL_session_reused(clientssl)))
3683         goto end;
3684
3685     SSL_SESSION_free(clntsess);
3686     clntsess = NULL;
3687     SSL_shutdown(clientssl);
3688     SSL_shutdown(serverssl);
3689     SSL_free(serverssl);
3690     SSL_free(clientssl);
3691     serverssl = clientssl = NULL;
3692
3693     /* Create a session based on SHA384 */
3694     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
3695             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3696                                           &clientssl, NULL, NULL))
3697             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3698                                                 SSL_ERROR_NONE)))
3699         goto end;
3700
3701     clntsess = SSL_get1_session(clientssl);
3702     SSL_shutdown(clientssl);
3703     SSL_shutdown(serverssl);
3704     SSL_free(serverssl);
3705     SSL_free(clientssl);
3706     serverssl = clientssl = NULL;
3707
3708     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3709                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
3710             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
3711                                                    "TLS_AES_256_GCM_SHA384"))
3712             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3713                                              NULL, NULL))
3714             || !TEST_true(SSL_set_session(clientssl, clntsess))
3715                /*
3716                 * We use SSL_ERROR_WANT_READ below so that we can pause the
3717                 * connection after the initial ClientHello has been sent to
3718                 * enable us to make some session changes.
3719                 */
3720             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3721                                                 SSL_ERROR_WANT_READ)))
3722         goto end;
3723
3724     /* Trick the client into thinking this session is for a different digest */
3725     clntsess->cipher = aes_128_gcm_sha256;
3726     clntsess->cipher_id = clntsess->cipher->id;
3727
3728     /*
3729      * Continue the previously started connection. Server has selected a SHA-384
3730      * ciphersuite, but client thinks the session is for SHA-256, so it should
3731      * bail out.
3732      */
3733     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
3734                                                 SSL_ERROR_SSL))
3735             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
3736                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
3737         goto end;
3738
3739     testresult = 1;
3740
3741  end:
3742     SSL_SESSION_free(clntsess);
3743     SSL_free(serverssl);
3744     SSL_free(clientssl);
3745     SSL_CTX_free(sctx);
3746     SSL_CTX_free(cctx);
3747
3748     return testresult;
3749 }
3750
3751 /*
3752  * Test TLSv1.3 Key exchange
3753  * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server
3754  * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server
3755  * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server
3756  * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server
3757  * Test 4 = Test NID_X25519 with TLSv1.3 client and server
3758  * Test 5 = Test NID_X448 with TLSv1.3 client and server
3759  * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server
3760  * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server
3761  * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server
3762  * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server
3763  * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server
3764  * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server
3765  * Test 12 = Test all ECDHE with TLSv1.2 client and server
3766  * Test 13 = Test all FFDHE with TLSv1.2 client and server
3767  */
3768 static int test_key_exchange(int idx)
3769 {
3770     SSL_CTX *sctx = NULL, *cctx = NULL;
3771     SSL *serverssl = NULL, *clientssl = NULL;
3772     int testresult = 0;
3773 # ifndef OPENSSL_NO_EC
3774     int ecdhe_kexch_groups[] = {NID_X9_62_prime256v1, NID_secp384r1,
3775                                 NID_secp521r1, NID_X25519, NID_X448};
3776 # endif
3777 # ifndef OPENSSL_NO_DH
3778     int ffdhe_kexch_groups[] = {NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096,
3779                                 NID_ffdhe6144, NID_ffdhe8192};
3780 # endif
3781     int kexch_alg;
3782     int *kexch_groups = &kexch_alg;
3783     int kexch_groups_size = 1;
3784     int max_version = TLS1_3_VERSION;
3785
3786     switch (idx) {
3787 # ifndef OPENSSL_NO_EC
3788 # ifndef OPENSSL_NO_TLS1_2
3789         case 12:
3790             max_version = TLS1_2_VERSION;
3791 # endif
3792             /* Fall through */
3793         case 0:
3794             kexch_groups = ecdhe_kexch_groups;
3795             kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups);
3796             break;
3797         case 1:
3798             kexch_alg = NID_X9_62_prime256v1;
3799             break;
3800         case 2:
3801             kexch_alg = NID_secp384r1;
3802             break;
3803         case 3:
3804             kexch_alg = NID_secp521r1;
3805             break;
3806         case 4:
3807             kexch_alg = NID_X25519;
3808             break;
3809         case 5:
3810             kexch_alg = NID_X448;
3811             break;
3812 # endif
3813 # ifndef OPENSSL_NO_DH
3814 # ifndef OPENSSL_NO_TLS1_2
3815         case 13:
3816             max_version = TLS1_2_VERSION;
3817 # endif
3818             /* Fall through */
3819         case 6:
3820             kexch_groups = ffdhe_kexch_groups;
3821             kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups);
3822             break;
3823         case 7:
3824             kexch_alg = NID_ffdhe2048;
3825             break;
3826         case 8:
3827             kexch_alg = NID_ffdhe3072;
3828             break;
3829         case 9:
3830             kexch_alg = NID_ffdhe4096;
3831             break;
3832         case 10:
3833             kexch_alg = NID_ffdhe6144;
3834             break;
3835         case 11:
3836             kexch_alg = NID_ffdhe8192;
3837             break;
3838 # endif
3839         default:
3840             /* We're skipping this test */
3841             return 1;
3842     }
3843
3844     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3845                                        TLS1_VERSION, max_version,
3846                                        &sctx, &cctx, cert, privkey)))
3847         goto end;
3848
3849     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx,
3850                    TLS1_3_RFC_AES_128_GCM_SHA256)))
3851         goto end;
3852
3853     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3854                    TLS1_3_RFC_AES_128_GCM_SHA256)))
3855         goto end;
3856
3857     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
3858                    TLS1_TXT_RSA_WITH_AES_128_SHA)))
3859         goto end;
3860
3861     /*
3862      * Must include an EC ciphersuite so that we send supported groups in
3863      * TLSv1.2
3864      */
3865 # ifndef OPENSSL_NO_TLS1_2
3866     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
3867                    TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM ":"
3868                    TLS1_TXT_RSA_WITH_AES_128_SHA)))
3869         goto end;
3870 # endif
3871
3872     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3873                                              NULL, NULL)))
3874         goto end;
3875
3876     if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
3877         || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
3878         goto end;
3879
3880     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
3881         goto end;
3882
3883     /*
3884      * If Handshake succeeds the negotiated kexch alg should be the first one in
3885      * configured, except in the case of FFDHE groups (idx 13), which are
3886      * TLSv1.3 only so we expect no shared group to exist.
3887      */
3888     if (!TEST_int_eq(SSL_get_shared_group(serverssl, 0),
3889                      idx == 13 ? 0 : kexch_groups[0]))
3890         goto end;
3891     if (max_version == TLS1_3_VERSION) {
3892         if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), kexch_groups[0]))
3893             goto end;
3894         if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), kexch_groups[0]))
3895             goto end;
3896     }
3897
3898     testresult = 1;
3899  end:
3900     SSL_free(serverssl);
3901     SSL_free(clientssl);
3902     SSL_CTX_free(sctx);
3903     SSL_CTX_free(cctx);
3904     return testresult;
3905 }
3906
3907 /*
3908  * Test TLSv1.3 Cipher Suite
3909  * Test 0 = Set TLS1.3 cipher on context
3910  * Test 1 = Set TLS1.3 cipher on SSL
3911  * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
3912  * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
3913  */
3914 static int test_tls13_ciphersuite(int idx)
3915 {
3916     SSL_CTX *sctx = NULL, *cctx = NULL;
3917     SSL *serverssl = NULL, *clientssl = NULL;
3918     static const char *t13_ciphers[] = {
3919         TLS1_3_RFC_AES_128_GCM_SHA256,
3920         TLS1_3_RFC_AES_256_GCM_SHA384,
3921         TLS1_3_RFC_AES_128_CCM_SHA256,
3922 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3923         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
3924         TLS1_3_RFC_AES_256_GCM_SHA384 ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
3925 # endif
3926         TLS1_3_RFC_AES_128_CCM_8_SHA256 ":" TLS1_3_RFC_AES_128_CCM_SHA256
3927     };
3928     const char *t13_cipher = NULL;
3929     const char *t12_cipher = NULL;
3930     const char *negotiated_scipher;
3931     const char *negotiated_ccipher;
3932     int set_at_ctx = 0;
3933     int set_at_ssl = 0;
3934     int testresult = 0;
3935     int max_ver;
3936     size_t i;
3937
3938     switch (idx) {
3939         case 0:
3940             set_at_ctx = 1;
3941             break;
3942         case 1:
3943             set_at_ssl = 1;
3944             break;
3945         case 2:
3946             set_at_ctx = 1;
3947             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
3948             break;
3949         case 3:
3950             set_at_ssl = 1;
3951             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
3952             break;
3953     }
3954
3955     for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
3956 # ifdef OPENSSL_NO_TLS1_2
3957         if (max_ver == TLS1_2_VERSION)
3958             continue;
3959 # endif
3960         for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
3961             t13_cipher = t13_ciphers[i];
3962             if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
3963                                                TLS_client_method(),
3964                                                TLS1_VERSION, max_ver,
3965                                                &sctx, &cctx, cert, privkey)))
3966                 goto end;
3967
3968             if (set_at_ctx) {
3969                 if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
3970                     || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
3971                     goto end;
3972                 if (t12_cipher != NULL) {
3973                     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
3974                         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
3975                                                               t12_cipher)))
3976                         goto end;
3977                 }
3978             }
3979
3980             if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3981                                               &clientssl, NULL, NULL)))
3982                 goto end;
3983
3984             if (set_at_ssl) {
3985                 if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
3986                     || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
3987                     goto end;
3988                 if (t12_cipher != NULL) {
3989                     if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
3990                         || !TEST_true(SSL_set_cipher_list(clientssl,
3991                                                           t12_cipher)))
3992                         goto end;
3993                 }
3994             }
3995
3996             if (!TEST_true(create_ssl_connection(serverssl, clientssl,
3997                                                  SSL_ERROR_NONE)))
3998                 goto end;
3999
4000             negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
4001                                                                  serverssl));
4002             negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
4003                                                                  clientssl));
4004             if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
4005                 goto end;
4006
4007             /*
4008              * TEST_strn_eq is used below because t13_cipher can contain
4009              * multiple ciphersuites
4010              */
4011             if (max_ver == TLS1_3_VERSION
4012                 && !TEST_strn_eq(t13_cipher, negotiated_scipher,
4013                                  strlen(negotiated_scipher)))
4014                 goto end;
4015
4016 # ifndef OPENSSL_NO_TLS1_2
4017             /* Below validation is not done when t12_cipher is NULL */
4018             if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
4019                 && !TEST_str_eq(t12_cipher, negotiated_scipher))
4020                 goto end;
4021 # endif
4022
4023             SSL_free(serverssl);
4024             serverssl = NULL;
4025             SSL_free(clientssl);
4026             clientssl = NULL;
4027             SSL_CTX_free(sctx);
4028             sctx = NULL;
4029             SSL_CTX_free(cctx);
4030             cctx = NULL;
4031         }
4032     }
4033
4034     testresult = 1;
4035  end:
4036     SSL_free(serverssl);
4037     SSL_free(clientssl);
4038     SSL_CTX_free(sctx);
4039     SSL_CTX_free(cctx);
4040     return testresult;
4041 }
4042
4043 /*
4044  * Test TLSv1.3 PSKs
4045  * Test 0 = Test new style callbacks
4046  * Test 1 = Test both new and old style callbacks
4047  * Test 2 = Test old style callbacks
4048  * Test 3 = Test old style callbacks with no certificate
4049  */
4050 static int test_tls13_psk(int idx)
4051 {
4052     SSL_CTX *sctx = NULL, *cctx = NULL;
4053     SSL *serverssl = NULL, *clientssl = NULL;
4054     const SSL_CIPHER *cipher = NULL;
4055     const unsigned char key[] = {
4056         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
4057         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4058         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
4059         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
4060     };
4061     int testresult = 0;
4062
4063     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4064                                        TLS1_VERSION, 0,
4065                                        &sctx, &cctx, idx == 3 ? NULL : cert,
4066                                        idx == 3 ? NULL : privkey)))
4067         goto end;
4068
4069     if (idx != 3) {
4070         /*
4071          * We use a ciphersuite with SHA256 to ease testing old style PSK
4072          * callbacks which will always default to SHA256. This should not be
4073          * necessary if we have no cert/priv key. In that case the server should
4074          * prefer SHA256 automatically.
4075          */
4076         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4077                                                 "TLS_AES_128_GCM_SHA256")))
4078             goto end;
4079     }
4080
4081     /*
4082      * Test 0: New style callbacks only
4083      * Test 1: New and old style callbacks (only the new ones should be used)
4084      * Test 2: Old style callbacks only
4085      */
4086     if (idx == 0 || idx == 1) {
4087         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
4088         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
4089     }
4090 #ifndef OPENSSL_NO_PSK
4091     if (idx >= 1) {
4092         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
4093         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
4094     }
4095 #endif
4096     srvid = pskid;
4097     use_session_cb_cnt = 0;
4098     find_session_cb_cnt = 0;
4099     psk_client_cb_cnt = 0;
4100     psk_server_cb_cnt = 0;
4101
4102     if (idx != 3) {
4103         /*
4104          * Check we can create a connection if callback decides not to send a
4105          * PSK
4106          */
4107         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4108                                                  NULL, NULL))
4109                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
4110                                                     SSL_ERROR_NONE))
4111                 || !TEST_false(SSL_session_reused(clientssl))
4112                 || !TEST_false(SSL_session_reused(serverssl)))
4113             goto end;
4114
4115         if (idx == 0 || idx == 1) {
4116             if (!TEST_true(use_session_cb_cnt == 1)
4117                     || !TEST_true(find_session_cb_cnt == 0)
4118                        /*
4119                         * If no old style callback then below should be 0
4120                         * otherwise 1
4121                         */
4122                     || !TEST_true(psk_client_cb_cnt == idx)
4123                     || !TEST_true(psk_server_cb_cnt == 0))
4124                 goto end;
4125         } else {
4126             if (!TEST_true(use_session_cb_cnt == 0)
4127                     || !TEST_true(find_session_cb_cnt == 0)
4128                     || !TEST_true(psk_client_cb_cnt == 1)
4129                     || !TEST_true(psk_server_cb_cnt == 0))
4130                 goto end;
4131         }
4132
4133         shutdown_ssl_connection(serverssl, clientssl);
4134         serverssl = clientssl = NULL;
4135         use_session_cb_cnt = psk_client_cb_cnt = 0;
4136     }
4137
4138     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4139                                              NULL, NULL)))
4140         goto end;
4141
4142     /* Create the PSK */
4143     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
4144     clientpsk = SSL_SESSION_new();
4145     if (!TEST_ptr(clientpsk)
4146             || !TEST_ptr(cipher)
4147             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
4148                                                       sizeof(key)))
4149             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
4150             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
4151                                                            TLS1_3_VERSION))
4152             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
4153         goto end;
4154     serverpsk = clientpsk;
4155
4156     /* Check we can create a connection and the PSK is used */
4157     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
4158             || !TEST_true(SSL_session_reused(clientssl))
4159             || !TEST_true(SSL_session_reused(serverssl)))
4160         goto end;
4161
4162     if (idx == 0 || idx == 1) {
4163         if (!TEST_true(use_session_cb_cnt == 1)
4164                 || !TEST_true(find_session_cb_cnt == 1)
4165                 || !TEST_true(psk_client_cb_cnt == 0)
4166                 || !TEST_true(psk_server_cb_cnt == 0))
4167             goto end;
4168     } else {
4169         if (!TEST_true(use_session_cb_cnt == 0)
4170                 || !TEST_true(find_session_cb_cnt == 0)
4171                 || !TEST_true(psk_client_cb_cnt == 1)
4172                 || !TEST_true(psk_server_cb_cnt == 1))
4173             goto end;
4174     }
4175
4176     shutdown_ssl_connection(serverssl, clientssl);
4177     serverssl = clientssl = NULL;
4178     use_session_cb_cnt = find_session_cb_cnt = 0;
4179     psk_client_cb_cnt = psk_server_cb_cnt = 0;
4180
4181     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4182                                              NULL, NULL)))
4183         goto end;
4184
4185     /* Force an HRR */
4186 #if defined(OPENSSL_NO_EC)
4187     if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
4188         goto end;
4189 #else
4190     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
4191         goto end;
4192 #endif
4193
4194     /*
4195      * Check we can create a connection, the PSK is used and the callbacks are
4196      * called twice.
4197      */
4198     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
4199             || !TEST_true(SSL_session_reused(clientssl))
4200             || !TEST_true(SSL_session_reused(serverssl)))
4201         goto end;
4202
4203     if (idx == 0 || idx == 1) {
4204         if (!TEST_true(use_session_cb_cnt == 2)
4205                 || !TEST_true(find_session_cb_cnt == 2)
4206                 || !TEST_true(psk_client_cb_cnt == 0)
4207                 || !TEST_true(psk_server_cb_cnt == 0))
4208             goto end;
4209     } else {
4210         if (!TEST_true(use_session_cb_cnt == 0)
4211                 || !TEST_true(find_session_cb_cnt == 0)
4212                 || !TEST_true(psk_client_cb_cnt == 2)
4213                 || !TEST_true(psk_server_cb_cnt == 2))
4214             goto end;
4215     }
4216
4217     shutdown_ssl_connection(serverssl, clientssl);
4218     serverssl = clientssl = NULL;
4219     use_session_cb_cnt = find_session_cb_cnt = 0;
4220     psk_client_cb_cnt = psk_server_cb_cnt = 0;
4221
4222     if (idx != 3) {
4223         /*
4224          * Check that if the server rejects the PSK we can still connect, but with
4225          * a full handshake
4226          */
4227         srvid = "Dummy Identity";
4228         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4229                                                  NULL, NULL))
4230                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
4231                                                     SSL_ERROR_NONE))
4232                 || !TEST_false(SSL_session_reused(clientssl))
4233                 || !TEST_false(SSL_session_reused(serverssl)))
4234             goto end;
4235
4236         if (idx == 0 || idx == 1) {
4237             if (!TEST_true(use_session_cb_cnt == 1)
4238                     || !TEST_true(find_session_cb_cnt == 1)
4239                     || !TEST_true(psk_client_cb_cnt == 0)
4240                        /*
4241                         * If no old style callback then below should be 0
4242                         * otherwise 1
4243                         */
4244                     || !TEST_true(psk_server_cb_cnt == idx))
4245                 goto end;
4246         } else {
4247             if (!TEST_true(use_session_cb_cnt == 0)
4248                     || !TEST_true(find_session_cb_cnt == 0)
4249                     || !TEST_true(psk_client_cb_cnt == 1)
4250                     || !TEST_true(psk_server_cb_cnt == 1))
4251                 goto end;
4252         }
4253
4254         shutdown_ssl_connection(serverssl, clientssl);
4255         serverssl = clientssl = NULL;
4256     }
4257     testresult = 1;
4258
4259  end:
4260     SSL_SESSION_free(clientpsk);
4261     SSL_SESSION_free(serverpsk);
4262     clientpsk = serverpsk = NULL;
4263     SSL_free(serverssl);
4264     SSL_free(clientssl);
4265     SSL_CTX_free(sctx);
4266     SSL_CTX_free(cctx);
4267     return testresult;
4268 }
4269
4270 static unsigned char cookie_magic_value[] = "cookie magic";
4271
4272 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
4273                                     unsigned int *cookie_len)
4274 {
4275     /*
4276      * Not suitable as a real cookie generation function but good enough for
4277      * testing!
4278      */
4279     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
4280     *cookie_len = sizeof(cookie_magic_value) - 1;
4281
4282     return 1;
4283 }
4284
4285 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
4286                                   unsigned int cookie_len)
4287 {
4288     if (cookie_len == sizeof(cookie_magic_value) - 1
4289         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
4290         return 1;
4291
4292     return 0;
4293 }
4294
4295 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
4296                                         size_t *cookie_len)
4297 {
4298     unsigned int temp;
4299     int res = generate_cookie_callback(ssl, cookie, &temp);
4300     *cookie_len = temp;
4301     return res;
4302 }
4303
4304 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
4305                                       size_t cookie_len)
4306 {
4307     return verify_cookie_callback(ssl, cookie, cookie_len);
4308 }
4309
4310 static int test_stateless(void)
4311 {
4312     SSL_CTX *sctx = NULL, *cctx = NULL;
4313     SSL *serverssl = NULL, *clientssl = NULL;
4314     int testresult = 0;
4315
4316     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4317                                        TLS1_VERSION, 0,
4318                                        &sctx, &cctx, cert, privkey)))
4319         goto end;
4320
4321     /* The arrival of CCS messages can confuse the test */
4322     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
4323
4324     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4325                                       NULL, NULL))
4326                /* Send the first ClientHello */
4327             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4328                                                  SSL_ERROR_WANT_READ))
4329                /*
4330                 * This should fail with a -1 return because we have no callbacks
4331                 * set up
4332                 */
4333             || !TEST_int_eq(SSL_stateless(serverssl), -1))
4334         goto end;
4335
4336     /* Fatal error so abandon the connection from this client */
4337     SSL_free(clientssl);
4338     clientssl = NULL;
4339
4340     /* Set up the cookie generation and verification callbacks */
4341     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
4342     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
4343
4344     /*
4345      * Create a new connection from the client (we can reuse the server SSL
4346      * object).
4347      */
4348     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4349                                              NULL, NULL))
4350                /* Send the first ClientHello */
4351             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4352                                                 SSL_ERROR_WANT_READ))
4353                /* This should fail because there is no cookie */
4354             || !TEST_int_eq(SSL_stateless(serverssl), 0))
4355         goto end;
4356
4357     /* Abandon the connection from this client */
4358     SSL_free(clientssl);
4359     clientssl = NULL;
4360
4361     /*
4362      * Now create a connection from a new client but with the same server SSL
4363      * object
4364      */
4365     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4366                                              NULL, NULL))
4367                /* Send the first ClientHello */
4368             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4369                                                 SSL_ERROR_WANT_READ))
4370                /* This should fail because there is no cookie */
4371             || !TEST_int_eq(SSL_stateless(serverssl), 0)
4372                /* Send the second ClientHello */
4373             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4374                                                 SSL_ERROR_WANT_READ))
4375                /* This should succeed because a cookie is now present */
4376             || !TEST_int_eq(SSL_stateless(serverssl), 1)
4377                /* Complete the connection */
4378             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4379                                                 SSL_ERROR_NONE)))
4380         goto end;
4381
4382     shutdown_ssl_connection(serverssl, clientssl);
4383     serverssl = clientssl = NULL;
4384     testresult = 1;
4385
4386  end:
4387     SSL_free(serverssl);
4388     SSL_free(clientssl);
4389     SSL_CTX_free(sctx);
4390     SSL_CTX_free(cctx);
4391     return testresult;
4392
4393 }
4394 #endif /* OPENSSL_NO_TLS1_3 */
4395
4396 static int clntaddoldcb = 0;
4397 static int clntparseoldcb = 0;
4398 static int srvaddoldcb = 0;
4399 static int srvparseoldcb = 0;
4400 static int clntaddnewcb = 0;
4401 static int clntparsenewcb = 0;
4402 static int srvaddnewcb = 0;
4403 static int srvparsenewcb = 0;
4404 static int snicb = 0;
4405
4406 #define TEST_EXT_TYPE1  0xff00
4407
4408 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
4409                       size_t *outlen, int *al, void *add_arg)
4410 {
4411     int *server = (int *)add_arg;
4412     unsigned char *data;
4413
4414     if (SSL_is_server(s))
4415         srvaddoldcb++;
4416     else
4417         clntaddoldcb++;
4418
4419     if (*server != SSL_is_server(s)
4420             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
4421         return -1;
4422
4423     *data = 1;
4424     *out = data;
4425     *outlen = sizeof(char);
4426     return 1;
4427 }
4428
4429 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
4430                         void *add_arg)
4431 {
4432     OPENSSL_free((unsigned char *)out);
4433 }
4434
4435 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
4436                         size_t inlen, int *al, void *parse_arg)
4437 {
4438     int *server = (int *)parse_arg;
4439
4440     if (SSL_is_server(s))
4441         srvparseoldcb++;
4442     else
4443         clntparseoldcb++;
4444
4445     if (*server != SSL_is_server(s)
4446             || inlen != sizeof(char)
4447             || *in != 1)
4448         return -1;
4449
4450     return 1;
4451 }
4452
4453 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
4454                       const unsigned char **out, size_t *outlen, X509 *x,
4455                       size_t chainidx, int *al, void *add_arg)
4456 {
4457     int *server = (int *)add_arg;
4458     unsigned char *data;
4459
4460     if (SSL_is_server(s))
4461         srvaddnewcb++;
4462     else
4463         clntaddnewcb++;
4464
4465     if (*server != SSL_is_server(s)
4466             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
4467         return -1;
4468
4469     *data = 1;
4470     *out = data;
4471     *outlen = sizeof(*data);
4472     return 1;
4473 }
4474
4475 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
4476                         const unsigned char *out, void *add_arg)
4477 {
4478     OPENSSL_free((unsigned char *)out);
4479 }
4480
4481 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
4482                         const unsigned char *in, size_t inlen, X509 *x,
4483                         size_t chainidx, int *al, void *parse_arg)
4484 {
4485     int *server = (int *)parse_arg;
4486
4487     if (SSL_is_server(s))
4488         srvparsenewcb++;
4489     else
4490         clntparsenewcb++;
4491
4492     if (*server != SSL_is_server(s)
4493             || inlen != sizeof(char) || *in != 1)
4494         return -1;
4495
4496     return 1;
4497 }
4498
4499 static int sni_cb(SSL *s, int *al, void *arg)
4500 {
4501     SSL_CTX *ctx = (SSL_CTX *)arg;
4502
4503     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
4504         *al = SSL_AD_INTERNAL_ERROR;
4505         return SSL_TLSEXT_ERR_ALERT_FATAL;
4506     }
4507     snicb++;
4508     return SSL_TLSEXT_ERR_OK;
4509 }
4510
4511 /*
4512  * Custom call back tests.
4513  * Test 0: Old style callbacks in TLSv1.2
4514  * Test 1: New style callbacks in TLSv1.2
4515  * Test 2: New style callbacks in TLSv1.2 with SNI
4516  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
4517  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
4518  */
4519 static int test_custom_exts(int tst)
4520 {
4521     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
4522     SSL *clientssl = NULL, *serverssl = NULL;
4523     int testresult = 0;
4524     static int server = 1;
4525     static int client = 0;
4526     SSL_SESSION *sess = NULL;
4527     unsigned int context;
4528
4529 #if defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_3)
4530     /* Skip tests for TLSv1.2 and below in this case */
4531     if (tst < 3)
4532         return 1;
4533 #endif
4534
4535     /* Reset callback counters */
4536     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
4537     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
4538     snicb = 0;
4539
4540     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4541                                        TLS1_VERSION, 0,
4542                                        &sctx, &cctx, cert, privkey)))
4543         goto end;
4544
4545     if (tst == 2
4546             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL,
4547                                               TLS1_VERSION, 0,
4548                                               &sctx2, NULL, cert, privkey)))
4549         goto end;
4550
4551
4552     if (tst < 3) {
4553         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
4554         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
4555         if (sctx2 != NULL)
4556             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
4557     }
4558
4559     if (tst == 4) {
4560         context = SSL_EXT_CLIENT_HELLO
4561                   | SSL_EXT_TLS1_2_SERVER_HELLO
4562                   | SSL_EXT_TLS1_3_SERVER_HELLO
4563                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
4564                   | SSL_EXT_TLS1_3_CERTIFICATE
4565                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
4566     } else {
4567         context = SSL_EXT_CLIENT_HELLO
4568                   | SSL_EXT_TLS1_2_SERVER_HELLO
4569                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
4570     }
4571
4572     /* Create a client side custom extension */
4573     if (tst == 0) {
4574         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
4575                                                      old_add_cb, old_free_cb,
4576                                                      &client, old_parse_cb,
4577                                                      &client)))
4578             goto end;
4579     } else {
4580         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
4581                                               new_add_cb, new_free_cb,
4582                                               &client, new_parse_cb, &client)))
4583             goto end;
4584     }
4585
4586     /* Should not be able to add duplicates */
4587     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
4588                                                   old_add_cb, old_free_cb,
4589                                                   &client, old_parse_cb,
4590                                                   &client))
4591             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
4592                                                   context, new_add_cb,
4593                                                   new_free_cb, &client,
4594                                                   new_parse_cb, &client)))
4595         goto end;
4596
4597     /* Create a server side custom extension */
4598     if (tst == 0) {
4599         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
4600                                                      old_add_cb, old_free_cb,
4601                                                      &server, old_parse_cb,
4602                                                      &server)))
4603             goto end;
4604     } else {
4605         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
4606                                               new_add_cb, new_free_cb,
4607                                               &server, new_parse_cb, &server)))
4608             goto end;
4609         if (sctx2 != NULL
4610                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
4611                                                      context, new_add_cb,
4612                                                      new_free_cb, &server,
4613                                                      new_parse_cb, &server)))
4614             goto end;
4615     }
4616
4617     /* Should not be able to add duplicates */
4618     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
4619                                                   old_add_cb, old_free_cb,
4620                                                   &server, old_parse_cb,
4621                                                   &server))
4622             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
4623                                                   context, new_add_cb,
4624                                                   new_free_cb, &server,
4625                                                   new_parse_cb, &server)))
4626         goto end;
4627
4628     if (tst == 2) {
4629         /* Set up SNI */
4630         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
4631                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
4632             goto end;
4633     }
4634
4635     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4636                                       &clientssl, NULL, NULL))
4637             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4638                                                 SSL_ERROR_NONE)))
4639         goto end;
4640
4641     if (tst == 0) {
4642         if (clntaddoldcb != 1
4643                 || clntparseoldcb != 1
4644                 || srvaddoldcb != 1
4645                 || srvparseoldcb != 1)
4646             goto end;
4647     } else if (tst == 1 || tst == 2 || tst == 3) {
4648         if (clntaddnewcb != 1
4649                 || clntparsenewcb != 1
4650                 || srvaddnewcb != 1
4651                 || srvparsenewcb != 1
4652                 || (tst != 2 && snicb != 0)
4653                 || (tst == 2 && snicb != 1))
4654             goto end;
4655     } else {
4656         /* In this case there 2 NewSessionTicket messages created */
4657         if (clntaddnewcb != 1
4658                 || clntparsenewcb != 5
4659                 || srvaddnewcb != 5
4660                 || srvparsenewcb != 1)
4661             goto end;
4662     }
4663
4664     sess = SSL_get1_session(clientssl);
4665     SSL_shutdown(clientssl);
4666     SSL_shutdown(serverssl);
4667     SSL_free(serverssl);
4668     SSL_free(clientssl);
4669     serverssl = clientssl = NULL;
4670
4671     if (tst == 3) {
4672         /* We don't bother with the resumption aspects for this test */
4673         testresult = 1;
4674         goto end;
4675     }
4676
4677     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4678                                       NULL, NULL))
4679             || !TEST_true(SSL_set_session(clientssl, sess))
4680             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4681                                                SSL_ERROR_NONE)))
4682         goto end;
4683
4684     /*
4685      * For a resumed session we expect to add the ClientHello extension. For the
4686      * old style callbacks we ignore it on the server side because they set
4687      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
4688      * them.
4689      */
4690     if (tst == 0) {
4691         if (clntaddoldcb != 2
4692                 || clntparseoldcb != 1
4693                 || srvaddoldcb != 1
4694                 || srvparseoldcb != 1)
4695             goto end;
4696     } else if (tst == 1 || tst == 2 || tst == 3) {
4697         if (clntaddnewcb != 2
4698                 || clntparsenewcb != 2
4699                 || srvaddnewcb != 2
4700                 || srvparsenewcb != 2)
4701             goto end;
4702     } else {
4703         /*
4704          * No Certificate message extensions in the resumption handshake,
4705          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
4706          */
4707         if (clntaddnewcb != 2
4708                 || clntparsenewcb != 8
4709                 || srvaddnewcb != 8
4710                 || srvparsenewcb != 2)
4711             goto end;
4712     }
4713
4714     testresult = 1;
4715
4716 end:
4717     SSL_SESSION_free(sess);
4718     SSL_free(serverssl);
4719     SSL_free(clientssl);
4720     SSL_CTX_free(sctx2);
4721     SSL_CTX_free(sctx);
4722     SSL_CTX_free(cctx);
4723     return testresult;
4724 }
4725
4726 /*
4727  * Test loading of serverinfo data in various formats. test_sslmessages actually
4728  * tests to make sure the extensions appear in the handshake
4729  */
4730 static int test_serverinfo(int tst)
4731 {
4732     unsigned int version;
4733     unsigned char *sibuf;
4734     size_t sibuflen;
4735     int ret, expected, testresult = 0;
4736     SSL_CTX *ctx;
4737
4738     ctx = SSL_CTX_new(TLS_method());
4739     if (!TEST_ptr(ctx))
4740         goto end;
4741
4742     if ((tst & 0x01) == 0x01)
4743         version = SSL_SERVERINFOV2;
4744     else
4745         version = SSL_SERVERINFOV1;
4746
4747     if ((tst & 0x02) == 0x02) {
4748         sibuf = serverinfov2;
4749         sibuflen = sizeof(serverinfov2);
4750         expected = (version == SSL_SERVERINFOV2);
4751     } else {
4752         sibuf = serverinfov1;
4753         sibuflen = sizeof(serverinfov1);
4754         expected = (version == SSL_SERVERINFOV1);
4755     }
4756
4757     if ((tst & 0x04) == 0x04) {
4758         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
4759     } else {
4760         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
4761
4762         /*
4763          * The version variable is irrelevant in this case - it's what is in the
4764          * buffer that matters
4765          */
4766         if ((tst & 0x02) == 0x02)
4767             expected = 0;
4768         else
4769             expected = 1;
4770     }
4771
4772     if (!TEST_true(ret == expected))
4773         goto end;
4774
4775     testresult = 1;
4776
4777  end:
4778     SSL_CTX_free(ctx);
4779
4780     return testresult;
4781 }
4782
4783 /*
4784  * Test that SSL_export_keying_material() produces expected results. There are
4785  * no test vectors so all we do is test that both sides of the communication
4786  * produce the same results for different protocol versions.
4787  */
4788 #define SMALL_LABEL_LEN 10
4789 #define LONG_LABEL_LEN  249
4790 static int test_export_key_mat(int tst)
4791 {
4792     int testresult = 0;
4793     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
4794     SSL *clientssl = NULL, *serverssl = NULL;
4795     const char label[LONG_LABEL_LEN + 1] = "test label";
4796     const unsigned char context[] = "context";
4797     const unsigned char *emptycontext = NULL;
4798     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
4799     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
4800     size_t labellen;
4801     const int protocols[] = {
4802         TLS1_VERSION,
4803         TLS1_1_VERSION,
4804         TLS1_2_VERSION,
4805         TLS1_3_VERSION,
4806         TLS1_3_VERSION,
4807         TLS1_3_VERSION
4808     };
4809
4810 #ifdef OPENSSL_NO_TLS1
4811     if (tst == 0)
4812         return 1;
4813 #endif
4814 #ifdef OPENSSL_NO_TLS1_1
4815     if (tst == 1)
4816         return 1;
4817 #endif
4818 #ifdef OPENSSL_NO_TLS1_2
4819     if (tst == 2)
4820         return 1;
4821 #endif
4822 #ifdef OPENSSL_NO_TLS1_3
4823     if (tst >= 3)
4824         return 1;
4825 #endif
4826     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4827                                        TLS1_VERSION, 0,
4828                                        &sctx, &cctx, cert, privkey)))
4829         goto end;
4830
4831     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
4832     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
4833     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
4834
4835     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
4836                                       NULL))
4837             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4838                                                 SSL_ERROR_NONE)))
4839         goto end;
4840
4841     if (tst == 5) {
4842         /*
4843          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
4844          * go over that.
4845          */
4846         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
4847                                                     sizeof(ckeymat1), label,
4848                                                     LONG_LABEL_LEN + 1, context,
4849                                                     sizeof(context) - 1, 1), 0))
4850             goto end;
4851
4852         testresult = 1;
4853         goto end;
4854     } else if (tst == 4) {
4855         labellen = LONG_LABEL_LEN;
4856     } else {
4857         labellen = SMALL_LABEL_LEN;
4858     }
4859
4860     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
4861                                                 sizeof(ckeymat1), label,
4862                                                 labellen, context,
4863                                                 sizeof(context) - 1, 1), 1)
4864             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
4865                                                        sizeof(ckeymat2), label,
4866                                                        labellen,
4867                                                        emptycontext,
4868                                                        0, 1), 1)
4869             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
4870                                                        sizeof(ckeymat3), label,
4871                                                        labellen,
4872                                                        NULL, 0, 0), 1)
4873             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
4874                                                        sizeof(skeymat1), label,
4875                                                        labellen,
4876                                                        context,
4877                                                        sizeof(context) -1, 1),
4878                             1)
4879             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
4880                                                        sizeof(skeymat2), label,
4881                                                        labellen,
4882                                                        emptycontext,
4883                                                        0, 1), 1)
4884             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
4885                                                        sizeof(skeymat3), label,
4886                                                        labellen,
4887                                                        NULL, 0, 0), 1)
4888                /*
4889                 * Check that both sides created the same key material with the
4890                 * same context.
4891                 */
4892             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
4893                             sizeof(skeymat1))
4894                /*
4895                 * Check that both sides created the same key material with an
4896                 * empty context.
4897                 */
4898             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
4899                             sizeof(skeymat2))
4900                /*
4901                 * Check that both sides created the same key material without a
4902                 * context.
4903                 */
4904             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
4905                             sizeof(skeymat3))
4906                /* Different contexts should produce different results */
4907             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
4908                             sizeof(ckeymat2)))
4909         goto end;
4910
4911     /*
4912      * Check that an empty context and no context produce different results in
4913      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
4914      */
4915     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
4916                                   sizeof(ckeymat3)))
4917             || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
4918                                          sizeof(ckeymat3))))
4919         goto end;
4920
4921     testresult = 1;
4922
4923  end:
4924     SSL_free(serverssl);
4925     SSL_free(clientssl);
4926     SSL_CTX_free(sctx2);
4927     SSL_CTX_free(sctx);
4928     SSL_CTX_free(cctx);
4929
4930     return testresult;
4931 }
4932
4933 #ifndef OPENSSL_NO_TLS1_3
4934 /*
4935  * Test that SSL_export_keying_material_early() produces expected
4936  * results. There are no test vectors so all we do is test that both
4937  * sides of the communication produce the same results for different
4938  * protocol versions.
4939  */
4940 static int test_export_key_mat_early(int idx)
4941 {
4942     static const char label[] = "test label";
4943     static const unsigned char context[] = "context";
4944     int testresult = 0;
4945     SSL_CTX *cctx = NULL, *sctx = NULL;
4946     SSL *clientssl = NULL, *serverssl = NULL;
4947     SSL_SESSION *sess = NULL;
4948     const unsigned char *emptycontext = NULL;
4949     unsigned char ckeymat1[80], ckeymat2[80];
4950     unsigned char skeymat1[80], skeymat2[80];
4951     unsigned char buf[1];
4952     size_t readbytes, written;
4953
4954     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
4955                                         &sess, idx)))
4956         goto end;
4957
4958     /* Here writing 0 length early data is enough. */
4959     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
4960             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4961                                                 &readbytes),
4962                             SSL_READ_EARLY_DATA_ERROR)
4963             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4964                             SSL_EARLY_DATA_ACCEPTED))
4965         goto end;
4966
4967     if (!TEST_int_eq(SSL_export_keying_material_early(
4968                      clientssl, ckeymat1, sizeof(ckeymat1), label,
4969                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
4970             || !TEST_int_eq(SSL_export_keying_material_early(
4971                             clientssl, ckeymat2, sizeof(ckeymat2), label,
4972                             sizeof(label) - 1, emptycontext, 0), 1)
4973             || !TEST_int_eq(SSL_export_keying_material_early(
4974                             serverssl, skeymat1, sizeof(skeymat1), label,
4975                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
4976             || !TEST_int_eq(SSL_export_keying_material_early(
4977                             serverssl, skeymat2, sizeof(skeymat2), label,
4978                             sizeof(label) - 1, emptycontext, 0), 1)
4979                /*
4980                 * Check that both sides created the same key material with the
4981                 * same context.
4982                 */
4983             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
4984                             sizeof(skeymat1))
4985                /*
4986                 * Check that both sides created the same key material with an
4987                 * empty context.
4988                 */
4989             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
4990                             sizeof(skeymat2))
4991                /* Different contexts should produce different results */
4992             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
4993                             sizeof(ckeymat2)))
4994         goto end;
4995
4996     testresult = 1;
4997
4998  end:
4999     SSL_SESSION_free(sess);
5000     SSL_SESSION_free(clientpsk);
5001     SSL_SESSION_free(serverpsk);
5002     clientpsk = serverpsk = NULL;
5003     SSL_free(serverssl);
5004     SSL_free(clientssl);
5005     SSL_CTX_free(sctx);
5006     SSL_CTX_free(cctx);
5007
5008     return testresult;
5009 }
5010
5011 #define NUM_KEY_UPDATE_MESSAGES 40
5012 /*
5013  * Test KeyUpdate.
5014  */
5015 static int test_key_update(void)
5016 {
5017     SSL_CTX *cctx = NULL, *sctx = NULL;
5018     SSL *clientssl = NULL, *serverssl = NULL;
5019     int testresult = 0, i, j;
5020     char buf[20];
5021     static char *mess = "A test message";
5022
5023     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5024                                        TLS_client_method(),
5025                                        TLS1_3_VERSION,
5026                                        0,
5027                                        &sctx, &cctx, cert, privkey))
5028             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5029                                              NULL, NULL))
5030             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5031                                                 SSL_ERROR_NONE)))
5032         goto end;
5033
5034     for (j = 0; j < 2; j++) {
5035         /* Send lots of KeyUpdate messages */
5036         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
5037             if (!TEST_true(SSL_key_update(clientssl,
5038                                           (j == 0)
5039                                           ? SSL_KEY_UPDATE_NOT_REQUESTED
5040                                           : SSL_KEY_UPDATE_REQUESTED))
5041                     || !TEST_true(SSL_do_handshake(clientssl)))
5042                 goto end;
5043         }
5044
5045         /* Check that sending and receiving app data is ok */
5046         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
5047                 || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
5048                                          strlen(mess)))
5049             goto end;
5050
5051         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
5052                 || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
5053                                          strlen(mess)))
5054             goto end;
5055     }
5056
5057     testresult = 1;
5058
5059  end:
5060     SSL_free(serverssl);
5061     SSL_free(clientssl);
5062     SSL_CTX_free(sctx);
5063     SSL_CTX_free(cctx);
5064
5065     return testresult;
5066 }
5067
5068 /*
5069  * Test we can handle a KeyUpdate (update requested) message while write data
5070  * is pending.
5071  * Test 0: Client sends KeyUpdate while Server is writing
5072  * Test 1: Server sends KeyUpdate while Client is writing
5073  */
5074 static int test_key_update_in_write(int tst)
5075 {
5076     SSL_CTX *cctx = NULL, *sctx = NULL;
5077     SSL *clientssl = NULL, *serverssl = NULL;
5078     int testresult = 0;
5079     char buf[20];
5080     static char *mess = "A test message";
5081     BIO *bretry = BIO_new(bio_s_always_retry());
5082     BIO *tmp = NULL;
5083     SSL *peerupdate = NULL, *peerwrite = NULL;
5084
5085     if (!TEST_ptr(bretry)
5086             || !TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5087                                               TLS_client_method(),
5088                                               TLS1_3_VERSION,
5089                                               0,
5090                                               &sctx, &cctx, cert, privkey))
5091             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5092                                              NULL, NULL))
5093             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5094                                                 SSL_ERROR_NONE)))
5095         goto end;
5096
5097     peerupdate = tst == 0 ? clientssl : serverssl;
5098     peerwrite = tst == 0 ? serverssl : clientssl;
5099
5100     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
5101             || !TEST_true(SSL_do_handshake(peerupdate)))
5102         goto end;
5103
5104     /* Swap the writing endpoint's write BIO to force a retry */
5105     tmp = SSL_get_wbio(peerwrite);
5106     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
5107         tmp = NULL;
5108         goto end;
5109     }
5110     SSL_set0_wbio(peerwrite, bretry);
5111     bretry = NULL;
5112
5113     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
5114     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
5115             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE))
5116         goto end;
5117
5118     /* Reinstate the original writing endpoint's write BIO */
5119     SSL_set0_wbio(peerwrite, tmp);
5120     tmp = NULL;
5121
5122     /* Now read some data - we will read the key update */
5123     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
5124             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ))
5125         goto end;
5126
5127     /*
5128      * Complete the write we started previously and read it from the other
5129      * endpoint
5130      */
5131     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
5132             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
5133         goto end;
5134
5135     /* Write more data to ensure we send the KeyUpdate message back */
5136     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
5137             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
5138         goto end;
5139
5140     testresult = 1;
5141
5142  end:
5143     SSL_free(serverssl);
5144     SSL_free(clientssl);
5145     SSL_CTX_free(sctx);
5146     SSL_CTX_free(cctx);
5147     BIO_free(bretry);
5148     BIO_free(tmp);
5149
5150     return testresult;
5151 }
5152 #endif /* OPENSSL_NO_TLS1_3 */
5153
5154 static int test_ssl_clear(int idx)
5155 {
5156     SSL_CTX *cctx = NULL, *sctx = NULL;
5157     SSL *clientssl = NULL, *serverssl = NULL;
5158     int testresult = 0;
5159
5160 #ifdef OPENSSL_NO_TLS1_2
5161     if (idx == 1)
5162         return 1;
5163 #endif
5164
5165     /* Create an initial connection */
5166     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
5167                                        TLS1_VERSION, 0,
5168                                        &sctx, &cctx, cert, privkey))
5169             || (idx == 1
5170                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
5171                                                             TLS1_2_VERSION)))
5172             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5173                                           &clientssl, NULL, NULL))
5174             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5175                                                 SSL_ERROR_NONE)))
5176         goto end;
5177
5178     SSL_shutdown(clientssl);
5179     SSL_shutdown(serverssl);
5180     SSL_free(serverssl);
5181     serverssl = NULL;
5182
5183     /* Clear clientssl - we're going to reuse the object */
5184     if (!TEST_true(SSL_clear(clientssl)))
5185         goto end;
5186
5187     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5188                                              NULL, NULL))
5189             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5190                                                 SSL_ERROR_NONE))
5191             || !TEST_true(SSL_session_reused(clientssl)))
5192         goto end;
5193
5194     SSL_shutdown(clientssl);
5195     SSL_shutdown(serverssl);
5196
5197     testresult = 1;
5198
5199  end:
5200     SSL_free(serverssl);
5201     SSL_free(clientssl);
5202     SSL_CTX_free(sctx);
5203     SSL_CTX_free(cctx);
5204
5205     return testresult;
5206 }
5207
5208 /* Parse CH and retrieve any MFL extension value if present */
5209 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
5210 {
5211     long len;
5212     unsigned char *data;
5213     PACKET pkt, pkt2, pkt3;
5214     unsigned int MFL_code = 0, type = 0;
5215
5216     if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
5217         goto end;
5218
5219     memset(&pkt, 0, sizeof(pkt));
5220     memset(&pkt2, 0, sizeof(pkt2));
5221     memset(&pkt3, 0, sizeof(pkt3));
5222
5223     if (!TEST_true( PACKET_buf_init( &pkt, data, len ) )
5224                /* Skip the record header */
5225             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
5226                /* Skip the handshake message header */
5227             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
5228                /* Skip client version and random */
5229             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
5230                                                + SSL3_RANDOM_SIZE))
5231                /* Skip session id */
5232             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
5233                /* Skip ciphers */
5234             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
5235                /* Skip compression */
5236             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
5237                /* Extensions len */
5238             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
5239         goto end;
5240
5241     /* Loop through all extensions */
5242     while (PACKET_remaining(&pkt2)) {
5243         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
5244                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
5245             goto end;
5246
5247         if (type == TLSEXT_TYPE_max_fragment_length) {
5248             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
5249                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
5250                 goto end;
5251
5252             *mfl_codemfl_code = MFL_code;
5253             return 1;
5254         }
5255     }
5256
5257  end:
5258     return 0;
5259 }
5260
5261 /* Maximum-Fragment-Length TLS extension mode to test */
5262 static const unsigned char max_fragment_len_test[] = {
5263     TLSEXT_max_fragment_length_512,
5264     TLSEXT_max_fragment_length_1024,
5265     TLSEXT_max_fragment_length_2048,
5266     TLSEXT_max_fragment_length_4096
5267 };
5268
5269 static int test_max_fragment_len_ext(int idx_tst)
5270 {
5271     SSL_CTX *ctx;
5272     SSL *con = NULL;
5273     int testresult = 0, MFL_mode = 0;
5274     BIO *rbio, *wbio;
5275
5276     ctx = SSL_CTX_new(TLS_method());
5277     if (!TEST_ptr(ctx))
5278         goto end;
5279
5280     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
5281                    ctx, max_fragment_len_test[idx_tst])))
5282         goto end;
5283
5284     con = SSL_new(ctx);
5285     if (!TEST_ptr(con))
5286         goto end;
5287
5288     rbio = BIO_new(BIO_s_mem());
5289     wbio = BIO_new(BIO_s_mem());
5290     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
5291         BIO_free(rbio);
5292         BIO_free(wbio);
5293         goto end;
5294     }
5295
5296     SSL_set_bio(con, rbio, wbio);
5297     SSL_set_connect_state(con);
5298
5299     if (!TEST_int_le(SSL_connect(con), 0)) {
5300         /* This shouldn't succeed because we don't have a server! */
5301         goto end;
5302     }
5303
5304     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
5305         /* no MFL in client hello */
5306         goto end;
5307     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
5308         goto end;
5309
5310     testresult = 1;
5311
5312 end:
5313     SSL_free(con);
5314     SSL_CTX_free(ctx);
5315
5316     return testresult;
5317 }
5318
5319 #ifndef OPENSSL_NO_TLS1_3
5320 static int test_pha_key_update(void)
5321 {
5322     SSL_CTX *cctx = NULL, *sctx = NULL;
5323     SSL *clientssl = NULL, *serverssl = NULL;
5324     int testresult = 0;
5325
5326     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
5327                                        TLS1_VERSION, 0,
5328                                        &sctx, &cctx, cert, privkey)))
5329         return 0;
5330
5331     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
5332         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
5333         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
5334         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
5335         goto end;
5336
5337     SSL_CTX_set_post_handshake_auth(cctx, 1);
5338
5339     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5340                                       NULL, NULL)))
5341         goto end;
5342
5343     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5344                                          SSL_ERROR_NONE)))
5345         goto end;
5346
5347     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
5348     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
5349         goto end;
5350
5351     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
5352         goto end;
5353
5354     /* Start handshake on the server */
5355     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
5356         goto end;
5357
5358     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
5359     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5360                                          SSL_ERROR_NONE)))
5361         goto end;
5362
5363     SSL_shutdown(clientssl);
5364     SSL_shutdown(serverssl);
5365
5366     testresult = 1;
5367
5368  end:
5369     SSL_free(serverssl);
5370     SSL_free(clientssl);
5371     SSL_CTX_free(sctx);
5372     SSL_CTX_free(cctx);
5373     return testresult;
5374 }
5375 #endif
5376
5377 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
5378
5379 static SRP_VBASE *vbase = NULL;
5380
5381 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
5382 {
5383     int ret = SSL3_AL_FATAL;
5384     char *username;
5385     SRP_user_pwd *user = NULL;
5386
5387     username = SSL_get_srp_username(s);
5388     if (username == NULL) {
5389         *ad = SSL_AD_INTERNAL_ERROR;
5390         goto err;
5391     }
5392
5393     user = SRP_VBASE_get1_by_user(vbase, username);
5394     if (user == NULL) {
5395         *ad = SSL_AD_INTERNAL_ERROR;
5396         goto err;
5397     }
5398
5399     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
5400                                  user->info) <= 0) {
5401         *ad = SSL_AD_INTERNAL_ERROR;
5402         goto err;
5403     }
5404
5405     ret = 0;
5406
5407  err:
5408     SRP_user_pwd_free(user);
5409     return ret;
5410 }
5411
5412 static int create_new_vfile(char *userid, char *password, const char *filename)
5413 {
5414     char *gNid = NULL;
5415     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
5416     TXT_DB *db = NULL;
5417     int ret = 0;
5418     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
5419     size_t i;
5420
5421     if (!TEST_ptr(dummy) || !TEST_ptr(row))
5422         goto end;
5423
5424     gNid = SRP_create_verifier(userid, password, &row[DB_srpsalt],
5425                                &row[DB_srpverifier], NULL, NULL);
5426     if (!TEST_ptr(gNid))
5427         goto end;
5428
5429     /*
5430      * The only way to create an empty TXT_DB is to provide a BIO with no data
5431      * in it!
5432      */
5433     db = TXT_DB_read(dummy, DB_NUMBER);
5434     if (!TEST_ptr(db))
5435         goto end;
5436
5437     out = BIO_new_file(filename, "w");
5438     if (!TEST_ptr(out))
5439         goto end;
5440
5441     row[DB_srpid] = OPENSSL_strdup(userid);
5442     row[DB_srptype] = OPENSSL_strdup("V");
5443     row[DB_srpgN] = OPENSSL_strdup(gNid);
5444
5445     if (!TEST_ptr(row[DB_srpid])
5446             || !TEST_ptr(row[DB_srptype])
5447             || !TEST_ptr(row[DB_srpgN])
5448             || !TEST_true(TXT_DB_insert(db, row)))
5449         goto end;
5450
5451     row = NULL;
5452
5453     if (!TXT_DB_write(out, db))
5454         goto end;
5455
5456     ret = 1;
5457  end:
5458     if (row != NULL) {
5459         for (i = 0; i < DB_NUMBER; i++)
5460             OPENSSL_free(row[i]);
5461     }
5462     OPENSSL_free(row);
5463     BIO_free(dummy);
5464     BIO_free(out);
5465     TXT_DB_free(db);
5466
5467     return ret;
5468 }
5469
5470 static int create_new_vbase(char *userid, char *password)
5471 {
5472     BIGNUM *verifier = NULL, *salt = NULL;
5473     const SRP_gN *lgN = NULL;
5474     SRP_user_pwd *user_pwd = NULL;
5475     int ret = 0;
5476
5477     lgN = SRP_get_default_gN(NULL);
5478     if (!TEST_ptr(lgN))
5479         goto end;
5480
5481     if (!TEST_true(SRP_create_verifier_BN(userid, password, &salt, &verifier,
5482                                           lgN->N, lgN->g)))
5483         goto end;
5484
5485     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
5486     if (!TEST_ptr(user_pwd))
5487         goto end;
5488
5489     user_pwd->N = lgN->N;
5490     user_pwd->g = lgN->g;
5491     user_pwd->id = OPENSSL_strdup(userid);
5492     if (!TEST_ptr(user_pwd->id))
5493         goto end;
5494
5495     user_pwd->v = verifier;
5496     user_pwd->s = salt;
5497     verifier = salt = NULL;
5498
5499     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
5500         goto end;
5501     user_pwd = NULL;
5502
5503     ret = 1;
5504 end:
5505     SRP_user_pwd_free(user_pwd);
5506     BN_free(salt);
5507     BN_free(verifier);
5508
5509     return ret;
5510 }
5511
5512 /*
5513  * SRP tests
5514  *
5515  * Test 0: Simple successful SRP connection, new vbase
5516  * Test 1: Connection failure due to bad password, new vbase
5517  * Test 2: Simple successful SRP connection, vbase loaded from existing file
5518  * Test 3: Connection failure due to bad password, vbase loaded from existing
5519  *         file
5520  * Test 4: Simple successful SRP connection, vbase loaded from new file
5521  * Test 5: Connection failure due to bad password, vbase loaded from new file
5522  */
5523 static int test_srp(int tst)
5524 {
5525     char *userid = "test", *password = "password", *tstsrpfile;
5526     SSL_CTX *cctx = NULL, *sctx = NULL;
5527     SSL *clientssl = NULL, *serverssl = NULL;
5528     int ret, testresult = 0;
5529
5530     vbase = SRP_VBASE_new(NULL);
5531     if (!TEST_ptr(vbase))
5532         goto end;
5533
5534     if (tst == 0 || tst == 1) {
5535         if (!TEST_true(create_new_vbase(userid, password)))
5536             goto end;
5537     } else {
5538         if (tst == 4 || tst == 5) {
5539             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
5540                 goto end;
5541             tstsrpfile = tmpfilename;
5542         } else {
5543             tstsrpfile = srpvfile;
5544         }
5545         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
5546             goto end;
5547     }
5548
5549     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
5550                                        TLS1_VERSION, 0,
5551                                        &sctx, &cctx, cert, privkey)))
5552         goto end;
5553
5554     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
5555             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
5556             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
5557             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
5558             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
5559         goto end;
5560
5561     if (tst % 2 == 1) {
5562         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
5563             goto end;
5564     } else {
5565         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
5566             goto end;
5567     }
5568
5569     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5570                                       NULL, NULL)))
5571         goto end;
5572
5573     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
5574     if (ret) {
5575         if (!TEST_true(tst % 2 == 0))
5576             goto end;
5577     } else {
5578         if (!TEST_true(tst % 2 == 1))
5579             goto end;
5580     }
5581
5582     testresult = 1;
5583
5584  end:
5585     SRP_VBASE_free(vbase);
5586     vbase = NULL;
5587     SSL_free(serverssl);
5588     SSL_free(clientssl);
5589     SSL_CTX_free(sctx);
5590     SSL_CTX_free(cctx);
5591
5592     return testresult;
5593 }
5594 #endif
5595
5596 static int info_cb_failed = 0;
5597 static int info_cb_offset = 0;
5598 static int info_cb_this_state = -1;
5599
5600 static struct info_cb_states_st {
5601     int where;
5602     const char *statestr;
5603 } info_cb_states[][60] = {
5604     {
5605         /* TLSv1.2 server followed by resumption */
5606         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5607         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5608         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
5609         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
5610         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
5611         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5612         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5613         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
5614         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
5615         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5616         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
5617         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5618         {SSL_CB_EXIT, NULL}, {0, NULL},
5619     }, {
5620         /* TLSv1.2 client followed by resumption */
5621         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5622         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5623         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
5624         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
5625         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
5626         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
5627         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
5628         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5629         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5630         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
5631         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
5632         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
5633     }, {
5634         /* TLSv1.3 server followed by resumption */
5635         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5636         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5637         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
5638         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
5639         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
5640         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
5641         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
5642         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5643         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5644         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
5645         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
5646         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5647         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
5648     }, {
5649         /* TLSv1.3 client followed by resumption */
5650         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5651         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5652         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
5653         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
5654         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
5655         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
5656         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "},
5657         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
5658         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
5659         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
5660         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
5661         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5662         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5663         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
5664         {SSL_CB_EXIT, NULL}, {0, NULL},
5665     }, {
5666         /* TLSv1.3 server, early_data */
5667         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5668         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5669         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
5670         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5671         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
5672         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
5673         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
5674         {SSL_CB_EXIT, NULL}, {0, NULL},
5675     }, {
5676         /* TLSv1.3 client, early_data */
5677         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5678         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
5679         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5680         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
5681         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
5682         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
5683         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5684         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
5685         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
5686     }, {
5687         {0, NULL},
5688     }
5689 };
5690
5691 static void sslapi_info_callback(const SSL *s, int where, int ret)
5692 {
5693     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
5694
5695     /* We do not ever expect a connection to fail in this test */
5696     if (!TEST_false(ret == 0)) {
5697         info_cb_failed = 1;
5698         return;
5699     }
5700
5701     /*
5702      * Do some sanity checks. We never expect these things to happen in this
5703      * test
5704      */
5705     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
5706             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
5707             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
5708         info_cb_failed = 1;
5709         return;
5710     }
5711
5712     /* Now check we're in the right state */
5713     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
5714         info_cb_failed = 1;
5715         return;
5716     }
5717     if ((where & SSL_CB_LOOP) != 0
5718             && !TEST_int_eq(strcmp(SSL_state_string(s),
5719                             state[info_cb_this_state].statestr), 0)) {
5720         info_cb_failed = 1;
5721         return;
5722     }
5723
5724     /*
5725      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
5726      */
5727     if ((where & SSL_CB_HANDSHAKE_DONE)
5728             && SSL_in_init((SSL *)s) != 0) {
5729         info_cb_failed = 1;
5730         return;
5731     }
5732 }
5733
5734 /*
5735  * Test the info callback gets called when we expect it to.
5736  *
5737  * Test 0: TLSv1.2, server
5738  * Test 1: TLSv1.2, client
5739  * Test 2: TLSv1.3, server
5740  * Test 3: TLSv1.3, client
5741  * Test 4: TLSv1.3, server, early_data
5742  * Test 5: TLSv1.3, client, early_data
5743  */
5744 static int test_info_callback(int tst)
5745 {
5746     SSL_CTX *cctx = NULL, *sctx = NULL;
5747     SSL *clientssl = NULL, *serverssl = NULL;
5748     SSL_SESSION *clntsess = NULL;
5749     int testresult = 0;
5750     int tlsvers;
5751
5752     if (tst < 2) {
5753 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
5754 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
5755                                     || !defined(OPENSSL_NO_DH))
5756         tlsvers = TLS1_2_VERSION;
5757 #else
5758         return 1;
5759 #endif
5760     } else {
5761 #ifndef OPENSSL_NO_TLS1_3
5762         tlsvers = TLS1_3_VERSION;
5763 #else
5764         return 1;
5765 #endif
5766     }
5767
5768     /* Reset globals */
5769     info_cb_failed = 0;
5770     info_cb_this_state = -1;
5771     info_cb_offset = tst;
5772
5773 #ifndef OPENSSL_NO_TLS1_3
5774     if (tst >= 4) {
5775         SSL_SESSION *sess = NULL;
5776         size_t written, readbytes;
5777         unsigned char buf[80];
5778
5779         /* early_data tests */
5780         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
5781                                             &serverssl, &sess, 0)))
5782             goto end;
5783
5784         /* We don't actually need this reference */
5785         SSL_SESSION_free(sess);
5786
5787         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
5788                               sslapi_info_callback);
5789
5790         /* Write and read some early data and then complete the connection */
5791         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
5792                                             &written))
5793                 || !TEST_size_t_eq(written, strlen(MSG1))
5794                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
5795                                                     sizeof(buf), &readbytes),
5796                                 SSL_READ_EARLY_DATA_SUCCESS)
5797                 || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
5798                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
5799                                 SSL_EARLY_DATA_ACCEPTED)
5800                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
5801                                                     SSL_ERROR_NONE))
5802                 || !TEST_false(info_cb_failed))
5803             goto end;
5804
5805         testresult = 1;
5806         goto end;
5807     }
5808 #endif
5809
5810     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5811                                        TLS_client_method(),
5812                                        tlsvers, tlsvers, &sctx, &cctx, cert,
5813                                        privkey)))
5814         goto end;
5815
5816     /*
5817      * For even numbered tests we check the server callbacks. For odd numbers we
5818      * check the client.
5819      */
5820     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
5821                               sslapi_info_callback);
5822
5823     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5824                                           &clientssl, NULL, NULL))
5825         || !TEST_true(create_ssl_connection(serverssl, clientssl,
5826                                             SSL_ERROR_NONE))
5827         || !TEST_false(info_cb_failed))
5828     goto end;
5829
5830
5831
5832     clntsess = SSL_get1_session(clientssl);
5833     SSL_shutdown(clientssl);
5834     SSL_shutdown(serverssl);
5835     SSL_free(serverssl);
5836     SSL_free(clientssl);
5837     serverssl = clientssl = NULL;
5838
5839     /* Now do a resumption */
5840     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
5841                                       NULL))
5842             || !TEST_true(SSL_set_session(clientssl, clntsess))
5843             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5844                                                 SSL_ERROR_NONE))
5845             || !TEST_true(SSL_session_reused(clientssl))
5846             || !TEST_false(info_cb_failed))
5847         goto end;
5848
5849     testresult = 1;
5850
5851  end:
5852     SSL_free(serverssl);
5853     SSL_free(clientssl);
5854     SSL_SESSION_free(clntsess);
5855     SSL_CTX_free(sctx);
5856     SSL_CTX_free(cctx);
5857     return testresult;
5858 }
5859
5860 static int test_ssl_pending(int tst)
5861 {
5862     SSL_CTX *cctx = NULL, *sctx = NULL;
5863     SSL *clientssl = NULL, *serverssl = NULL;
5864     int testresult = 0;
5865     char msg[] = "A test message";
5866     char buf[5];
5867     size_t written, readbytes;
5868
5869     if (tst == 0) {
5870         if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5871                                            TLS_client_method(),
5872                                            TLS1_VERSION, 0,
5873                                            &sctx, &cctx, cert, privkey)))
5874             goto end;
5875     } else {
5876 #ifndef OPENSSL_NO_DTLS
5877         if (!TEST_true(create_ssl_ctx_pair(DTLS_server_method(),
5878                                            DTLS_client_method(),
5879                                            DTLS1_VERSION, 0,
5880                                            &sctx, &cctx, cert, privkey)))
5881             goto end;
5882 #else
5883         return 1;
5884 #endif
5885     }
5886
5887     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5888                                              NULL, NULL))
5889             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5890                                                 SSL_ERROR_NONE)))
5891         goto end;
5892
5893     if (!TEST_int_eq(SSL_pending(clientssl), 0)
5894             || !TEST_false(SSL_has_pending(clientssl))
5895             || !TEST_int_eq(SSL_pending(serverssl), 0)
5896             || !TEST_false(SSL_has_pending(serverssl))
5897             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
5898             || !TEST_size_t_eq(written, sizeof(msg))
5899             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
5900             || !TEST_size_t_eq(readbytes, sizeof(buf))
5901             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
5902             || !TEST_true(SSL_has_pending(clientssl)))
5903         goto end;
5904
5905     testresult = 1;
5906
5907  end:
5908     SSL_free(serverssl);
5909     SSL_free(clientssl);
5910     SSL_CTX_free(sctx);
5911     SSL_CTX_free(cctx);
5912
5913     return testresult;
5914 }
5915
5916 static struct {
5917     unsigned int maxprot;
5918     const char *clntciphers;
5919     const char *clnttls13ciphers;
5920     const char *srvrciphers;
5921     const char *srvrtls13ciphers;
5922     const char *shared;
5923 } shared_ciphers_data[] = {
5924 /*
5925  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
5926  * TLSv1.3 is enabled but TLSv1.2 is disabled.
5927  */
5928 #if defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
5929     {
5930         TLS1_2_VERSION,
5931         "AES128-SHA:AES256-SHA",
5932         NULL,
5933         "AES256-SHA:DHE-RSA-AES128-SHA",
5934         NULL,
5935         "AES256-SHA"
5936     },
5937     {
5938         TLS1_2_VERSION,
5939         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
5940         NULL,
5941         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
5942         NULL,
5943         "AES128-SHA:AES256-SHA"
5944     },
5945     {
5946         TLS1_2_VERSION,
5947         "AES128-SHA:AES256-SHA",
5948         NULL,
5949         "AES128-SHA:DHE-RSA-AES128-SHA",
5950         NULL,
5951         "AES128-SHA"
5952     },
5953 #endif
5954 /*
5955  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
5956  * enabled.
5957  */
5958 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
5959     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
5960     {
5961         TLS1_3_VERSION,
5962         "AES128-SHA:AES256-SHA",
5963         NULL,
5964         "AES256-SHA:AES128-SHA256",
5965         NULL,
5966         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
5967         "TLS_AES_128_GCM_SHA256:AES256-SHA"
5968     },
5969 #endif
5970 #ifndef OPENSSL_NO_TLS1_3
5971     {
5972         TLS1_3_VERSION,
5973         "AES128-SHA",
5974         "TLS_AES_256_GCM_SHA384",
5975         "AES256-SHA",
5976         "TLS_AES_256_GCM_SHA384",
5977         "TLS_AES_256_GCM_SHA384"
5978     },
5979 #endif
5980 };
5981
5982 static int test_ssl_get_shared_ciphers(int tst)
5983 {
5984     SSL_CTX *cctx = NULL, *sctx = NULL;
5985     SSL *clientssl = NULL, *serverssl = NULL;
5986     int testresult = 0;
5987     char buf[1024];
5988
5989     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5990                                        TLS_client_method(),
5991                                        TLS1_VERSION,
5992                                        shared_ciphers_data[tst].maxprot,
5993                                        &sctx, &cctx, cert, privkey)))
5994         goto end;
5995
5996     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5997                                         shared_ciphers_data[tst].clntciphers))
5998             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
5999                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
6000                                     shared_ciphers_data[tst].clnttls13ciphers)))
6001             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
6002                                         shared_ciphers_data[tst].srvrciphers))
6003             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
6004                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
6005                                     shared_ciphers_data[tst].srvrtls13ciphers))))
6006         goto end;
6007
6008
6009     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6010                                              NULL, NULL))
6011             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6012                                                 SSL_ERROR_NONE)))
6013         goto end;
6014
6015     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
6016             || !TEST_int_eq(strcmp(buf, shared_ciphers_data[tst].shared), 0)) {
6017         TEST_info("Shared ciphers are: %s\n", buf);
6018         goto end;
6019     }
6020
6021     testresult = 1;
6022
6023  end:
6024     SSL_free(serverssl);
6025     SSL_free(clientssl);
6026     SSL_CTX_free(sctx);
6027     SSL_CTX_free(cctx);
6028
6029     return testresult;
6030 }
6031
6032 static const char *appdata = "Hello World";
6033 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
6034 static int tick_key_renew = 0;
6035 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
6036
6037 static int gen_tick_cb(SSL *s, void *arg)
6038 {
6039     gen_tick_called = 1;
6040
6041     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
6042                                            strlen(appdata));
6043 }
6044
6045 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
6046                                      const unsigned char *keyname,
6047                                      size_t keyname_length,
6048                                      SSL_TICKET_STATUS status,
6049                                      void *arg)
6050 {
6051     void *tickdata;
6052     size_t tickdlen;
6053
6054     dec_tick_called = 1;
6055
6056     if (status == SSL_TICKET_EMPTY)
6057         return SSL_TICKET_RETURN_IGNORE_RENEW;
6058
6059     if (!TEST_true(status == SSL_TICKET_SUCCESS
6060                    || status == SSL_TICKET_SUCCESS_RENEW))
6061         return SSL_TICKET_RETURN_ABORT;
6062
6063     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
6064                                                    &tickdlen))
6065             || !TEST_size_t_eq(tickdlen, strlen(appdata))
6066             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
6067         return SSL_TICKET_RETURN_ABORT;
6068
6069     if (tick_key_cb_called)  {
6070         /* Don't change what the ticket key callback wanted to do */
6071         switch (status) {
6072         case SSL_TICKET_NO_DECRYPT:
6073             return SSL_TICKET_RETURN_IGNORE_RENEW;
6074
6075         case SSL_TICKET_SUCCESS:
6076             return SSL_TICKET_RETURN_USE;
6077
6078         case SSL_TICKET_SUCCESS_RENEW:
6079             return SSL_TICKET_RETURN_USE_RENEW;
6080
6081         default:
6082             return SSL_TICKET_RETURN_ABORT;
6083         }
6084     }
6085     return tick_dec_ret;
6086
6087 }
6088
6089 #ifndef OPENSSL_NO_DEPRECATED_3_0
6090 static int tick_key_cb(SSL *s, unsigned char key_name[16],
6091                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
6092                        HMAC_CTX *hctx, int enc)
6093 {
6094     const unsigned char tick_aes_key[16] = "0123456789abcdef";
6095     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
6096
6097     tick_key_cb_called = 1;
6098     memset(iv, 0, AES_BLOCK_SIZE);
6099     memset(key_name, 0, 16);
6100     if (!EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, tick_aes_key, iv, enc)
6101             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key),
6102                              EVP_sha256(), NULL))
6103         return -1;
6104
6105     return tick_key_renew ? 2 : 1;
6106 }
6107 #endif
6108
6109 static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
6110                            unsigned char iv[EVP_MAX_IV_LENGTH],
6111                            EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
6112 {
6113     const unsigned char tick_aes_key[16] = "0123456789abcdef";
6114     unsigned char tick_hmac_key[16] = "0123456789abcdef";
6115     OSSL_PARAM params[3];
6116
6117     tick_key_cb_called = 1;
6118     memset(iv, 0, AES_BLOCK_SIZE);
6119     memset(key_name, 0, 16);
6120     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
6121                                                  "SHA256", 0);
6122     params[1] = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
6123                                                   tick_hmac_key,
6124                                                   sizeof(tick_hmac_key));
6125     params[2] = OSSL_PARAM_construct_end();
6126     if (!EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, tick_aes_key, iv, enc)
6127             || !EVP_MAC_CTX_set_params(hctx, params)
6128             || !EVP_MAC_init(hctx))
6129         return -1;
6130
6131     return tick_key_renew ? 2 : 1;
6132 }
6133
6134 /*
6135  * Test the various ticket callbacks
6136  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
6137  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
6138  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
6139  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
6140  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
6141  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
6142  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
6143  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
6144  * Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
6145  * Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
6146  * Test 10: TLSv1.2, old ticket key callback, ticket, renewal
6147  * Test 11: TLSv1.3, old ticket key callback, ticket, renewal
6148  * Test 12: TLSv1.2, ticket key callback, ticket, no renewal
6149  * Test 13: TLSv1.3, ticket key callback, ticket, no renewal
6150  * Test 14: TLSv1.2, ticket key callback, ticket, renewal
6151  * Test 15: TLSv1.3, ticket key callback, ticket, renewal
6152  */
6153 static int test_ticket_callbacks(int tst)
6154 {
6155     SSL_CTX *cctx = NULL, *sctx = NULL;
6156     SSL *clientssl = NULL, *serverssl = NULL;
6157     SSL_SESSION *clntsess = NULL;
6158     int testresult = 0;
6159
6160 #ifdef OPENSSL_NO_TLS1_2
6161     if (tst % 2 == 0)
6162         return 1;
6163 #endif
6164 #ifdef OPENSSL_NO_TLS1_3
6165     if (tst % 2 == 1)
6166         return 1;
6167 #endif
6168 #ifdef OPENSSL_NO_DEPRECATED_3_0
6169     if (tst >= 8 && tst <= 11)
6170         return 1;
6171 #endif
6172
6173     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
6174
6175     /* Which tests the ticket key callback should request renewal for */
6176     if (tst == 10 || tst == 11 || tst == 14 || tst == 15)
6177         tick_key_renew = 1;
6178     else
6179         tick_key_renew = 0;
6180
6181     /* Which tests the decrypt ticket callback should request renewal for */
6182     switch (tst) {
6183     case 0:
6184     case 1:
6185         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
6186         break;
6187
6188     case 2:
6189     case 3:
6190         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
6191         break;
6192
6193     case 4:
6194     case 5:
6195         tick_dec_ret = SSL_TICKET_RETURN_USE;
6196         break;
6197
6198     case 6:
6199     case 7:
6200         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
6201         break;
6202
6203     default:
6204         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
6205     }
6206
6207     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6208                                        TLS_client_method(),
6209                                        TLS1_VERSION,
6210                                        ((tst % 2) == 0) ? TLS1_2_VERSION
6211                                                         : TLS1_3_VERSION,
6212                                        &sctx, &cctx, cert, privkey)))
6213         goto end;
6214
6215     /*
6216      * We only want sessions to resume from tickets - not the session cache. So
6217      * switch the cache off.
6218      */
6219     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
6220         goto end;
6221
6222     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
6223                                                  NULL)))
6224         goto end;
6225
6226     if (tst >= 12) {
6227         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb)))
6228             goto end;
6229 #ifndef OPENSSL_NO_DEPRECATED_3_0
6230     } else if (tst >= 8) {
6231         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
6232             goto end;
6233 #endif
6234     }
6235
6236     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6237                                              NULL, NULL))
6238             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6239                                                 SSL_ERROR_NONE)))
6240         goto end;
6241
6242     /*
6243      * The decrypt ticket key callback in TLSv1.2 should be called even though
6244      * we have no ticket yet, because it gets called with a status of
6245      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
6246      * actually send any ticket data). This does not happen in TLSv1.3 because
6247      * it is not valid to send empty ticket data in TLSv1.3.
6248      */
6249     if (!TEST_int_eq(gen_tick_called, 1)
6250             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
6251         goto end;
6252
6253     gen_tick_called = dec_tick_called = 0;
6254
6255     clntsess = SSL_get1_session(clientssl);
6256     SSL_shutdown(clientssl);
6257     SSL_shutdown(serverssl);
6258     SSL_free(serverssl);
6259     SSL_free(clientssl);
6260     serverssl = clientssl = NULL;
6261
6262     /* Now do a resumption */
6263     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6264                                       NULL))
6265             || !TEST_true(SSL_set_session(clientssl, clntsess))
6266             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6267                                                 SSL_ERROR_NONE)))
6268         goto end;
6269
6270     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
6271             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW) {
6272         if (!TEST_false(SSL_session_reused(clientssl)))
6273             goto end;
6274     } else {
6275         if (!TEST_true(SSL_session_reused(clientssl)))
6276             goto end;
6277     }
6278
6279     if (!TEST_int_eq(gen_tick_called,
6280                      (tick_key_renew
6281                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
6282                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
6283                      ? 1 : 0)
6284             || !TEST_int_eq(dec_tick_called, 1))
6285         goto end;
6286
6287     testresult = 1;
6288
6289  end:
6290     SSL_SESSION_free(clntsess);
6291     SSL_free(serverssl);
6292     SSL_free(clientssl);
6293     SSL_CTX_free(sctx);
6294     SSL_CTX_free(cctx);
6295
6296     return testresult;
6297 }
6298
6299 /*
6300  * Test bi-directional shutdown.
6301  * Test 0: TLSv1.2
6302  * Test 1: TLSv1.2, server continues to read/write after client shutdown
6303  * Test 2: TLSv1.3, no pending NewSessionTicket messages
6304  * Test 3: TLSv1.3, pending NewSessionTicket messages
6305  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
6306  *                  sends key update, client reads it
6307  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
6308  *                  sends CertificateRequest, client reads and ignores it
6309  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
6310  *                  doesn't read it
6311  */
6312 static int test_shutdown(int tst)
6313 {
6314     SSL_CTX *cctx = NULL, *sctx = NULL;
6315     SSL *clientssl = NULL, *serverssl = NULL;
6316     int testresult = 0;
6317     char msg[] = "A test message";
6318     char buf[80];
6319     size_t written, readbytes;
6320     SSL_SESSION *sess;
6321
6322 #ifdef OPENSSL_NO_TLS1_2
6323     if (tst <= 1)
6324         return 1;
6325 #endif
6326 #ifdef OPENSSL_NO_TLS1_3
6327     if (tst >= 2)
6328         return 1;
6329 #endif
6330
6331     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6332                                        TLS_client_method(),
6333                                        TLS1_VERSION,
6334                                        (tst <= 1) ? TLS1_2_VERSION
6335                                                   : TLS1_3_VERSION,
6336                                        &sctx, &cctx, cert, privkey)))
6337         goto end;
6338
6339     if (tst == 5)
6340         SSL_CTX_set_post_handshake_auth(cctx, 1);
6341
6342     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6343                                              NULL, NULL)))
6344         goto end;
6345
6346     if (tst == 3) {
6347         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
6348                                                   SSL_ERROR_NONE, 1))
6349                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6350                 || !TEST_false(SSL_SESSION_is_resumable(sess)))
6351             goto end;
6352     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6353                                               SSL_ERROR_NONE))
6354             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6355             || !TEST_true(SSL_SESSION_is_resumable(sess))) {
6356         goto end;
6357     }
6358
6359     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
6360         goto end;
6361
6362     if (tst >= 4) {
6363         /*
6364          * Reading on the server after the client has sent close_notify should
6365          * fail and provide SSL_ERROR_ZERO_RETURN
6366          */
6367         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
6368                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
6369                                 SSL_ERROR_ZERO_RETURN)
6370                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
6371                                 SSL_RECEIVED_SHUTDOWN)
6372                    /*
6373                     * Even though we're shutdown on receive we should still be
6374                     * able to write.
6375                     */
6376                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
6377             goto end;
6378         if (tst == 4
6379                 && !TEST_true(SSL_key_update(serverssl,
6380                                              SSL_KEY_UPDATE_REQUESTED)))
6381             goto end;
6382         if (tst == 5) {
6383             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
6384             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
6385                 goto end;
6386         }
6387         if ((tst == 4 || tst == 5)
6388                 && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
6389             goto end;
6390         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
6391             goto end;
6392         if (tst == 4 || tst == 5) {
6393             /* Should still be able to read data from server */
6394             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
6395                                        &readbytes))
6396                     || !TEST_size_t_eq(readbytes, sizeof(msg))
6397                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
6398                     || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
6399                                               &readbytes))
6400                     || !TEST_size_t_eq(readbytes, sizeof(msg))
6401                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
6402                 goto end;
6403         }
6404     }
6405
6406     /* Writing on the client after sending close_notify shouldn't be possible */
6407     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
6408         goto end;
6409
6410     if (tst < 4) {
6411         /*
6412          * For these tests the client has sent close_notify but it has not yet
6413          * been received by the server. The server has not sent close_notify
6414          * yet.
6415          */
6416         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
6417                    /*
6418                     * Writing on the server after sending close_notify shouldn't
6419                     * be possible.
6420                     */
6421                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
6422                 || !TEST_int_eq(SSL_shutdown(clientssl), 1)
6423                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6424                 || !TEST_true(SSL_SESSION_is_resumable(sess))
6425                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
6426             goto end;
6427     } else if (tst == 4 || tst == 5) {
6428         /*
6429          * In this test the client has sent close_notify and it has been
6430          * received by the server which has responded with a close_notify. The
6431          * client needs to read the close_notify sent by the server.
6432          */
6433         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
6434                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6435                 || !TEST_true(SSL_SESSION_is_resumable(sess)))
6436             goto end;
6437     } else {
6438         /*
6439          * tst == 6
6440          *
6441          * The client has sent close_notify and is expecting a close_notify
6442          * back, but instead there is application data first. The shutdown
6443          * should fail with a fatal error.
6444          */
6445         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
6446                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
6447             goto end;
6448     }
6449
6450     testresult = 1;
6451
6452  end:
6453     SSL_free(serverssl);
6454     SSL_free(clientssl);
6455     SSL_CTX_free(sctx);
6456     SSL_CTX_free(cctx);
6457
6458     return testresult;
6459 }
6460
6461 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OPENSSL_NO_TLS1_3)
6462 static int cert_cb_cnt;
6463
6464 static int cert_cb(SSL *s, void *arg)
6465 {
6466     SSL_CTX *ctx = (SSL_CTX *)arg;
6467     BIO *in = NULL;
6468     EVP_PKEY *pkey = NULL;
6469     X509 *x509 = NULL, *rootx = NULL;
6470     STACK_OF(X509) *chain = NULL;
6471     char *rootfile = NULL, *ecdsacert = NULL, *ecdsakey = NULL;
6472     int ret = 0;
6473
6474     if (cert_cb_cnt == 0) {
6475         /* Suspend the handshake */
6476         cert_cb_cnt++;
6477         return -1;
6478     } else if (cert_cb_cnt == 1) {
6479         /*
6480          * Update the SSL_CTX, set the certificate and private key and then
6481          * continue the handshake normally.
6482          */
6483         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
6484             return 0;
6485
6486         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
6487                 || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
6488                                                       SSL_FILETYPE_PEM))
6489                 || !TEST_true(SSL_check_private_key(s)))
6490             return 0;
6491         cert_cb_cnt++;
6492         return 1;
6493     } else if (cert_cb_cnt == 3) {
6494         int rv;
6495
6496         rootfile = test_mk_file_path(certsdir, "rootcert.pem");
6497         ecdsacert = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
6498         ecdsakey = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
6499         if (!TEST_ptr(rootfile) || !TEST_ptr(ecdsacert) || !TEST_ptr(ecdsakey))
6500             goto out;
6501         chain = sk_X509_new_null();
6502         if (!TEST_ptr(chain))
6503             goto out;
6504         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6505                 || !TEST_int_ge(BIO_read_filename(in, rootfile), 0)
6506                 || !TEST_ptr(rootx = PEM_read_bio_X509(in, NULL, NULL, NULL))
6507                 || !TEST_true(sk_X509_push(chain, rootx)))
6508             goto out;
6509         rootx = NULL;
6510         BIO_free(in);
6511         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6512                 || !TEST_int_ge(BIO_read_filename(in, ecdsacert), 0)
6513                 || !TEST_ptr(x509 = PEM_read_bio_X509(in, NULL, NULL, NULL)))
6514             goto out;
6515         BIO_free(in);
6516         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6517                 || !TEST_int_ge(BIO_read_filename(in, ecdsakey), 0)
6518                 || !TEST_ptr(pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL)))
6519             goto out;
6520         rv = SSL_check_chain(s, x509, pkey, chain);
6521         /*
6522          * If the cert doesn't show as valid here (e.g., because we don't
6523          * have any shared sigalgs), then we will not set it, and there will
6524          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
6525          * will cause tls_choose_sigalgs() to fail the connection.
6526          */
6527         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
6528                 == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
6529             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
6530                 goto out;
6531         }
6532
6533         ret = 1;
6534     }
6535
6536     /* Abort the handshake */
6537  out:
6538     OPENSSL_free(ecdsacert);
6539     OPENSSL_free(ecdsakey);
6540     OPENSSL_free(rootfile);
6541     BIO_free(in);
6542     EVP_PKEY_free(pkey);
6543     X509_free(x509);
6544     X509_free(rootx);
6545     sk_X509_pop_free(chain, X509_free);
6546     return ret;
6547 }
6548
6549 /*
6550  * Test the certificate callback.
6551  * Test 0: Callback fails
6552  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
6553  * Test 2: Success - SSL_set_SSL_CTX() in the callback
6554  * Test 3: Success - Call SSL_check_chain from the callback
6555  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
6556  *                   chain
6557  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
6558  */
6559 static int test_cert_cb_int(int prot, int tst)
6560 {
6561     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
6562     SSL *clientssl = NULL, *serverssl = NULL;
6563     int testresult = 0, ret;
6564
6565 #ifdef OPENSSL_NO_EC
6566     /* We use an EC cert in these tests, so we skip in a no-ec build */
6567     if (tst >= 3)
6568         return 1;
6569 #endif
6570
6571     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6572                                        TLS_client_method(),
6573                                        TLS1_VERSION,
6574                                        prot,
6575                                        &sctx, &cctx, NULL, NULL)))
6576         goto end;
6577
6578     if (tst == 0)
6579         cert_cb_cnt = -1;
6580     else if (tst >= 3)
6581         cert_cb_cnt = 3;
6582     else
6583         cert_cb_cnt = 0;
6584
6585     if (tst == 2)
6586         snictx = SSL_CTX_new(TLS_server_method());
6587     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
6588
6589     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6590                                       NULL, NULL)))
6591         goto end;
6592
6593     if (tst == 4) {
6594         /*
6595          * We cause SSL_check_chain() to fail by specifying sig_algs that
6596          * the chain doesn't meet (the root uses an RSA cert)
6597          */
6598         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
6599                                              "ecdsa_secp256r1_sha256")))
6600             goto end;
6601     } else if (tst == 5) {
6602         /*
6603          * We cause SSL_check_chain() to fail by specifying sig_algs that
6604          * the ee cert doesn't meet (the ee uses an ECDSA cert)
6605          */
6606         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
6607                            "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
6608             goto end;
6609     }
6610
6611     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
6612     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
6613             || (tst > 0
6614                 && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
6615         goto end;
6616     }
6617
6618     testresult = 1;
6619
6620  end:
6621     SSL_free(serverssl);
6622     SSL_free(clientssl);
6623     SSL_CTX_free(sctx);
6624     SSL_CTX_free(cctx);
6625     SSL_CTX_free(snictx);
6626
6627     return testresult;
6628 }
6629 #endif
6630
6631 static int test_cert_cb(int tst)
6632 {
6633     int testresult = 1;
6634
6635 #ifndef OPENSSL_NO_TLS1_2
6636     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
6637 #endif
6638 #ifndef OPENSSL_NO_TLS1_3
6639     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
6640 #endif
6641
6642     return testresult;
6643 }
6644
6645 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
6646 {
6647     X509 *xcert, *peer;
6648     EVP_PKEY *privpkey;
6649     BIO *in = NULL;
6650
6651     /* Check that SSL_get_peer_certificate() returns something sensible */
6652     peer = SSL_get_peer_certificate(ssl);
6653     if (!TEST_ptr(peer))
6654         return 0;
6655     X509_free(peer);
6656
6657     in = BIO_new_file(cert, "r");
6658     if (!TEST_ptr(in))
6659         return 0;
6660
6661     xcert = PEM_read_bio_X509(in, NULL, NULL, NULL);
6662     BIO_free(in);
6663     if (!TEST_ptr(xcert))
6664         return 0;
6665
6666     in = BIO_new_file(privkey, "r");
6667     if (!TEST_ptr(in)) {
6668         X509_free(xcert);
6669         return 0;
6670     }
6671
6672     privpkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
6673     BIO_free(in);
6674     if (!TEST_ptr(privpkey)) {
6675         X509_free(xcert);
6676         return 0;
6677     }
6678
6679     *x509 = xcert;
6680     *pkey = privpkey;
6681
6682     return 1;
6683 }
6684
6685 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
6686 {
6687     return 1;
6688 }
6689
6690 static int test_client_cert_cb(int tst)
6691 {
6692     SSL_CTX *cctx = NULL, *sctx = NULL;
6693     SSL *clientssl = NULL, *serverssl = NULL;
6694     int testresult = 0;
6695
6696 #ifdef OPENSSL_NO_TLS1_2
6697     if (tst == 0)
6698         return 1;
6699 #endif
6700 #ifdef OPENSSL_NO_TLS1_3
6701     if (tst == 1)
6702         return 1;
6703 #endif
6704
6705     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6706                                        TLS_client_method(),
6707                                        TLS1_VERSION,
6708                                        tst == 0 ? TLS1_2_VERSION
6709                                                 : TLS1_3_VERSION,
6710                                        &sctx, &cctx, cert, privkey)))
6711         goto end;
6712
6713     /*
6714      * Test that setting a client_cert_cb results in a client certificate being
6715      * sent.
6716      */
6717     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
6718     SSL_CTX_set_verify(sctx,
6719                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
6720                        verify_cb);
6721
6722     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6723                                       NULL, NULL))
6724             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6725                                                 SSL_ERROR_NONE)))
6726         goto end;
6727
6728     testresult = 1;
6729
6730  end:
6731     SSL_free(serverssl);
6732     SSL_free(clientssl);
6733     SSL_CTX_free(sctx);
6734     SSL_CTX_free(cctx);
6735
6736     return testresult;
6737 }
6738
6739 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OPENSSL_NO_TLS1_3)
6740 /*
6741  * Test setting certificate authorities on both client and server.
6742  *
6743  * Test 0: SSL_CTX_set0_CA_list() only
6744  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
6745  * Test 2: Only SSL_CTX_set_client_CA_list()
6746  */
6747 static int test_ca_names_int(int prot, int tst)
6748 {
6749     SSL_CTX *cctx = NULL, *sctx = NULL;
6750     SSL *clientssl = NULL, *serverssl = NULL;
6751     int testresult = 0;
6752     size_t i;
6753     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
6754     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
6755     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
6756     const STACK_OF(X509_NAME) *sktmp = NULL;
6757
6758     for (i = 0; i < OSSL_NELEM(name); i++) {
6759         name[i] = X509_NAME_new();
6760         if (!TEST_ptr(name[i])
6761                 || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
6762                                                          MBSTRING_ASC,
6763                                                          (unsigned char *)
6764                                                          strnames[i],
6765                                                          -1, -1, 0)))
6766             goto end;
6767     }
6768
6769     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
6770                                        TLS_client_method(),
6771                                        TLS1_VERSION,
6772                                        prot,
6773                                        &sctx, &cctx, cert, privkey)))
6774         goto end;
6775
6776     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
6777
6778     if (tst == 0 || tst == 1) {
6779         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
6780                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
6781                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
6782                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
6783                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
6784                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
6785             goto end;
6786
6787         SSL_CTX_set0_CA_list(sctx, sk1);
6788         SSL_CTX_set0_CA_list(cctx, sk2);
6789         sk1 = sk2 = NULL;
6790     }
6791     if (tst == 1 || tst == 2) {
6792         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
6793                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
6794                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
6795                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
6796                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
6797                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
6798             goto end;
6799
6800         SSL_CTX_set_client_CA_list(sctx, sk1);
6801         SSL_CTX_set_client_CA_list(cctx, sk2);
6802         sk1 = sk2 = NULL;
6803     }
6804
6805     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6806                                       NULL, NULL))
6807             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6808                                                 SSL_ERROR_NONE)))
6809         goto end;
6810
6811     /*
6812      * We only expect certificate authorities to have been sent to the server
6813      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
6814      */
6815     sktmp = SSL_get0_peer_CA_list(serverssl);
6816     if (prot == TLS1_3_VERSION
6817             && (tst == 0 || tst == 1)) {
6818         if (!TEST_ptr(sktmp)
6819                 || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
6820                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
6821                                               name[0]), 0)
6822                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
6823                                               name[1]), 0))
6824             goto end;
6825     } else if (!TEST_ptr_null(sktmp)) {
6826         goto end;
6827     }
6828
6829     /*
6830      * In all tests we expect certificate authorities to have been sent to the
6831      * client. However, SSL_set_client_CA_list() should override
6832      * SSL_set0_CA_list()
6833      */
6834     sktmp = SSL_get0_peer_CA_list(clientssl);
6835     if (!TEST_ptr(sktmp)
6836             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
6837             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
6838                                           name[tst == 0 ? 0 : 2]), 0)
6839             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
6840                                           name[tst == 0 ? 1 : 3]), 0))
6841         goto end;
6842
6843     testresult = 1;
6844
6845  end:
6846     SSL_free(serverssl);
6847     SSL_free(clientssl);
6848     SSL_CTX_free(sctx);
6849     SSL_CTX_free(cctx);
6850     for (i = 0; i < OSSL_NELEM(name); i++)
6851         X509_NAME_free(name[i]);
6852     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
6853     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
6854
6855     return testresult;
6856 }
6857 #endif
6858
6859 static int test_ca_names(int tst)
6860 {
6861     int testresult = 1;
6862
6863 #ifndef OPENSSL_NO_TLS1_2
6864     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
6865 #endif
6866 #ifndef OPENSSL_NO_TLS1_3
6867     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
6868 #endif
6869
6870     return testresult;
6871 }
6872
6873 #ifndef OPENSSL_NO_TLS1_2
6874 static const char *multiblock_cipherlist_data[]=
6875 {
6876     "AES128-SHA",
6877     "AES128-SHA256",
6878     "AES256-SHA",
6879     "AES256-SHA256",
6880 };
6881
6882 /* Reduce the fragment size - so the multiblock test buffer can be small */
6883 # define MULTIBLOCK_FRAGSIZE 512
6884
6885 static int test_multiblock_write(int test_index)
6886 {
6887     static const char *fetchable_ciphers[]=
6888     {
6889         "AES-128-CBC-HMAC-SHA1",
6890         "AES-128-CBC-HMAC-SHA256",
6891         "AES-256-CBC-HMAC-SHA1",
6892         "AES-256-CBC-HMAC-SHA256"
6893     };
6894     const char *cipherlist = multiblock_cipherlist_data[test_index];
6895     const SSL_METHOD *smeth = TLS_server_method();
6896     const SSL_METHOD *cmeth = TLS_client_method();
6897     int min_version = TLS1_VERSION;
6898     int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */
6899     SSL_CTX *cctx = NULL, *sctx = NULL;
6900     SSL *clientssl = NULL, *serverssl = NULL;
6901     int testresult = 0;
6902
6903     /*
6904      * Choose a buffer large enough to perform a multi-block operation
6905      * i.e: write_len >= 4 * frag_size
6906      * 9 * is chosen so that multiple multiblocks are used + some leftover.
6907      */
6908     unsigned char msg[MULTIBLOCK_FRAGSIZE * 9];
6909     unsigned char buf[sizeof(msg)], *p = buf;
6910     size_t readbytes, written, len;
6911     EVP_CIPHER *ciph = NULL;
6912
6913     /*
6914      * Check if the cipher exists before attempting to use it since it only has
6915      * a hardware specific implementation.
6916      */
6917     ciph = EVP_CIPHER_fetch(NULL, fetchable_ciphers[test_index], "");
6918     if (ciph == NULL) {
6919         TEST_skip("Multiblock cipher is not available for %s", cipherlist);
6920         return 1;
6921     }
6922     EVP_CIPHER_free(ciph);
6923
6924     /* Set up a buffer with some data that will be sent to the client */
6925     RAND_bytes(msg, sizeof(msg));
6926
6927     if (!TEST_true(create_ssl_ctx_pair(smeth, cmeth, min_version, max_version,
6928                                        &sctx, &cctx, cert, privkey)))
6929         goto end;
6930
6931     if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE)))
6932         goto end;
6933
6934     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6935                                       NULL, NULL)))
6936             goto end;
6937
6938     /* settings to force it to use AES-CBC-HMAC_SHA */
6939     SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
6940     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist)))
6941        goto end;
6942
6943     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
6944         goto end;
6945
6946     if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
6947         || !TEST_size_t_eq(written, sizeof(msg)))
6948         goto end;
6949
6950     len = written;
6951     while (len > 0) {
6952         if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes)))
6953             goto end;
6954         p += readbytes;
6955         len -= readbytes;
6956     }
6957     if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf)))
6958         goto end;
6959
6960     testresult = 1;
6961 end:
6962     SSL_free(serverssl);
6963     SSL_free(clientssl);
6964     SSL_CTX_free(sctx);
6965     SSL_CTX_free(cctx);
6966
6967     return testresult;
6968 }
6969 #endif /* OPENSSL_NO_TLS1_2 */
6970
6971 OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile\n")
6972
6973 int setup_tests(void)
6974 {
6975     if (!TEST_ptr(certsdir = test_get_argument(0))
6976             || !TEST_ptr(srpvfile = test_get_argument(1))
6977             || !TEST_ptr(tmpfilename = test_get_argument(2)))
6978         return 0;
6979
6980     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
6981 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
6982         TEST_error("not supported in this build");
6983         return 0;
6984 #else
6985         int i, mcount, rcount, fcount;
6986
6987         for (i = 0; i < 4; i++)
6988             test_export_key_mat(i);
6989         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
6990         test_printf_stdout("malloc %d realloc %d free %d\n",
6991                 mcount, rcount, fcount);
6992         return 1;
6993 #endif
6994     }
6995
6996     cert = test_mk_file_path(certsdir, "servercert.pem");
6997     if (cert == NULL)
6998         return 0;
6999
7000     privkey = test_mk_file_path(certsdir, "serverkey.pem");
7001     if (privkey == NULL) {
7002         OPENSSL_free(cert);
7003         return 0;
7004     }
7005
7006 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_KTLS) \
7007     && !defined(OPENSSL_NO_SOCK)
7008     ADD_TEST(test_ktls_no_txrx_client_no_txrx_server);
7009     ADD_TEST(test_ktls_no_rx_client_no_txrx_server);
7010     ADD_TEST(test_ktls_no_tx_client_no_txrx_server);
7011     ADD_TEST(test_ktls_client_no_txrx_server);
7012     ADD_TEST(test_ktls_no_txrx_client_no_rx_server);
7013     ADD_TEST(test_ktls_no_rx_client_no_rx_server);
7014     ADD_TEST(test_ktls_no_tx_client_no_rx_server);
7015     ADD_TEST(test_ktls_client_no_rx_server);
7016     ADD_TEST(test_ktls_no_txrx_client_no_tx_server);
7017     ADD_TEST(test_ktls_no_rx_client_no_tx_server);
7018     ADD_TEST(test_ktls_no_tx_client_no_tx_server);
7019     ADD_TEST(test_ktls_client_no_tx_server);
7020     ADD_TEST(test_ktls_no_txrx_client_server);
7021     ADD_TEST(test_ktls_no_rx_client_server);
7022     ADD_TEST(test_ktls_no_tx_client_server);
7023     ADD_TEST(test_ktls_client_server);
7024     ADD_TEST(test_ktls_sendfile);
7025 #endif
7026     ADD_TEST(test_large_message_tls);
7027     ADD_TEST(test_large_message_tls_read_ahead);
7028 #ifndef OPENSSL_NO_DTLS
7029     ADD_TEST(test_large_message_dtls);
7030 #endif
7031 #ifndef OPENSSL_NO_OCSP
7032     ADD_TEST(test_tlsext_status_type);
7033 #endif
7034     ADD_TEST(test_session_with_only_int_cache);
7035     ADD_TEST(test_session_with_only_ext_cache);
7036     ADD_TEST(test_session_with_both_cache);
7037 #ifndef OPENSSL_NO_TLS1_3
7038     ADD_ALL_TESTS(test_stateful_tickets, 3);
7039     ADD_ALL_TESTS(test_stateless_tickets, 3);
7040     ADD_TEST(test_psk_tickets);
7041 #endif
7042     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
7043     ADD_TEST(test_ssl_bio_pop_next_bio);
7044     ADD_TEST(test_ssl_bio_pop_ssl_bio);
7045     ADD_TEST(test_ssl_bio_change_rbio);
7046     ADD_TEST(test_ssl_bio_change_wbio);
7047 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
7048     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
7049     ADD_TEST(test_keylog);
7050 #endif
7051 #ifndef OPENSSL_NO_TLS1_3
7052     ADD_TEST(test_keylog_no_master_key);
7053 #endif
7054 #ifndef OPENSSL_NO_TLS1_2
7055     ADD_TEST(test_client_hello_cb);
7056     ADD_TEST(test_no_ems);
7057 #endif
7058 #ifndef OPENSSL_NO_TLS1_3
7059     ADD_ALL_TESTS(test_early_data_read_write, 3);
7060     /*
7061      * We don't do replay tests for external PSK. Replay protection isn't used
7062      * in that scenario.
7063      */
7064     ADD_ALL_TESTS(test_early_data_replay, 2);
7065     ADD_ALL_TESTS(test_early_data_skip, 3);
7066     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
7067     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, 3);
7068     ADD_ALL_TESTS(test_early_data_skip_abort, 3);
7069     ADD_ALL_TESTS(test_early_data_not_sent, 3);
7070     ADD_ALL_TESTS(test_early_data_psk, 8);
7071     ADD_ALL_TESTS(test_early_data_not_expected, 3);
7072 # ifndef OPENSSL_NO_TLS1_2
7073     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
7074 # endif
7075 #endif
7076 #ifndef OPENSSL_NO_TLS1_3
7077     ADD_ALL_TESTS(test_set_ciphersuite, 10);
7078     ADD_TEST(test_ciphersuite_change);
7079     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
7080 # ifdef OPENSSL_NO_PSK
7081     ADD_ALL_TESTS(test_tls13_psk, 1);
7082 # else
7083     ADD_ALL_TESTS(test_tls13_psk, 4);
7084 # endif  /* OPENSSL_NO_PSK */
7085 # ifndef OPENSSL_NO_TLS1_2
7086     /* Test with both TLSv1.3 and 1.2 versions */
7087     ADD_ALL_TESTS(test_key_exchange, 14);
7088 # else
7089     /* Test with only TLSv1.3 versions */
7090     ADD_ALL_TESTS(test_key_exchange, 12);
7091 # endif
7092     ADD_ALL_TESTS(test_custom_exts, 5);
7093     ADD_TEST(test_stateless);
7094     ADD_TEST(test_pha_key_update);
7095 #else
7096     ADD_ALL_TESTS(test_custom_exts, 3);
7097 #endif
7098     ADD_ALL_TESTS(test_serverinfo, 8);
7099     ADD_ALL_TESTS(test_export_key_mat, 6);
7100 #ifndef OPENSSL_NO_TLS1_3
7101     ADD_ALL_TESTS(test_export_key_mat_early, 3);
7102     ADD_TEST(test_key_update);
7103     ADD_ALL_TESTS(test_key_update_in_write, 2);
7104 #endif
7105     ADD_ALL_TESTS(test_ssl_clear, 2);
7106     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
7107 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
7108     ADD_ALL_TESTS(test_srp, 6);
7109 #endif
7110     ADD_ALL_TESTS(test_info_callback, 6);
7111     ADD_ALL_TESTS(test_ssl_pending, 2);
7112     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
7113     ADD_ALL_TESTS(test_ticket_callbacks, 16);
7114     ADD_ALL_TESTS(test_shutdown, 7);
7115     ADD_ALL_TESTS(test_cert_cb, 6);
7116     ADD_ALL_TESTS(test_client_cert_cb, 2);
7117     ADD_ALL_TESTS(test_ca_names, 3);
7118 #ifndef OPENSSL_NO_TLS1_2
7119     ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data));
7120 #endif
7121     return 1;
7122 }
7123
7124 void cleanup_tests(void)
7125 {
7126     OPENSSL_free(cert);
7127     OPENSSL_free(privkey);
7128     bio_s_mempacket_test_free();
7129     bio_s_always_retry_free();
7130 }