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