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