10869cf15f02e93353e918e9cdfeb3d1fde9c3e1
[openssl.git] / test / sslapitest.c
1 /*
2  * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 <string.h>
11
12 #include <openssl/opensslconf.h>
13 #include <openssl/bio.h>
14 #include <openssl/crypto.h>
15 #include <openssl/ssl.h>
16 #include <openssl/ocsp.h>
17
18 #include "ssltestlib.h"
19 #include "testutil.h"
20 #include "internal/nelem.h"
21 #include "../ssl/ssl_locl.h"
22
23 static char *cert = NULL;
24 static char *privkey = NULL;
25
26 #define LOG_BUFFER_SIZE 1024
27 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
28 static size_t server_log_buffer_index = 0;
29 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
30 static size_t client_log_buffer_index = 0;
31 static int error_writing_log = 0;
32
33 #ifndef OPENSSL_NO_OCSP
34 static const unsigned char orespder[] = "Dummy OCSP Response";
35 static int ocsp_server_called = 0;
36 static int ocsp_client_called = 0;
37
38 static int cdummyarg = 1;
39 static X509 *ocspcert = NULL;
40 #endif
41
42 #define NUM_EXTRA_CERTS 40
43
44 /*
45  * This structure is used to validate that the correct number of log messages
46  * of various types are emitted when emitting secret logs.
47  */
48 struct sslapitest_log_counts {
49     unsigned int rsa_key_exchange_count;
50     unsigned int master_secret_count;
51     unsigned int client_handshake_secret_count;
52     unsigned int server_handshake_secret_count;
53     unsigned int client_application_secret_count;
54     unsigned int server_application_secret_count;
55 };
56
57
58 static unsigned char serverinfov1[] = {
59     0xff, 0xff, /* Dummy extension type */
60     0x00, 0x01, /* Extension length is 1 byte */
61     0xff        /* Dummy extension data */
62 };
63
64 static unsigned char serverinfov2[] = {
65     0x00, 0x00, 0x00,
66     (unsigned char)(SSL_EXT_CLIENT_HELLO & 0xff), /* Dummy context - 4 bytes */
67     0xff, 0xff, /* Dummy extension type */
68     0x00, 0x01, /* Extension length is 1 byte */
69     0xff        /* Dummy extension data */
70 };
71
72 static void client_keylog_callback(const SSL *ssl, const char *line)
73 {
74     int line_length = strlen(line);
75
76     /* If the log doesn't fit, error out. */
77     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
78         TEST_info("Client log too full");
79         error_writing_log = 1;
80         return;
81     }
82
83     strcat(client_log_buffer, line);
84     client_log_buffer_index += line_length;
85     client_log_buffer[client_log_buffer_index++] = '\n';
86 }
87
88 static void server_keylog_callback(const SSL *ssl, const char *line)
89 {
90     int line_length = strlen(line);
91
92     /* If the log doesn't fit, error out. */
93     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
94         TEST_info("Server log too full");
95         error_writing_log = 1;
96         return;
97     }
98
99     strcat(server_log_buffer, line);
100     server_log_buffer_index += line_length;
101     server_log_buffer[server_log_buffer_index++] = '\n';
102 }
103
104 static int compare_hex_encoded_buffer(const char *hex_encoded,
105                                       size_t hex_length,
106                                       const uint8_t *raw,
107                                       size_t raw_length)
108 {
109     size_t i, j;
110     char hexed[3];
111
112     if (!TEST_size_t_eq(raw_length * 2, hex_length))
113         return 1;
114
115     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
116         sprintf(hexed, "%02x", raw[i]);
117         if (!TEST_int_eq(hexed[0], hex_encoded[j])
118                 || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
119             return 1;
120     }
121
122     return 0;
123 }
124
125 static int test_keylog_output(char *buffer, const SSL *ssl,
126                               const SSL_SESSION *session,
127                               struct sslapitest_log_counts *expected)
128 {
129     char *token = NULL;
130     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0};
131     size_t client_random_size = SSL3_RANDOM_SIZE;
132     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
133     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
134     unsigned int rsa_key_exchange_count = 0;
135     unsigned int master_secret_count = 0;
136     unsigned int client_handshake_secret_count = 0;
137     unsigned int server_handshake_secret_count = 0;
138     unsigned int client_application_secret_count = 0;
139     unsigned int server_application_secret_count = 0;
140
141     for (token = strtok(buffer, " \n"); token != NULL;
142          token = strtok(NULL, " \n")) {
143         if (strcmp(token, "RSA") == 0) {
144             /*
145              * Premaster secret. Tokens should be: 16 ASCII bytes of
146              * hex-encoded encrypted secret, then the hex-encoded pre-master
147              * secret.
148              */
149             if (!TEST_ptr(token = strtok(NULL, " \n")))
150                 return 0;
151             if (!TEST_size_t_eq(strlen(token), 16))
152                 return 0;
153             if (!TEST_ptr(token = strtok(NULL, " \n")))
154                 return 0;
155             /*
156              * We can't sensibly check the log because the premaster secret is
157              * transient, and OpenSSL doesn't keep hold of it once the master
158              * secret is generated.
159              */
160             rsa_key_exchange_count++;
161         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
162             /*
163              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
164              * client random, then the hex-encoded master secret.
165              */
166             client_random_size = SSL_get_client_random(ssl,
167                                                        actual_client_random,
168                                                        SSL3_RANDOM_SIZE);
169             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
170                 return 0;
171
172             if (!TEST_ptr(token = strtok(NULL, " \n")))
173                 return 0;
174             if (!TEST_size_t_eq(strlen(token), 64))
175                 return 0;
176             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
177                                                        actual_client_random,
178                                                        client_random_size)))
179                 return 0;
180
181             if (!TEST_ptr(token = strtok(NULL, " \n")))
182                 return 0;
183             master_key_size = SSL_SESSION_get_master_key(session,
184                                                          actual_master_key,
185                                                          master_key_size);
186             if (!TEST_size_t_ne(master_key_size, 0))
187                 return 0;
188             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
189                                                        actual_master_key,
190                                                        master_key_size)))
191                 return 0;
192             master_secret_count++;
193         } else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
194                     || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
195                     || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
196                     || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0) {
197             /*
198              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
199              * client random, and then the hex-encoded secret. In this case,
200              * we treat all of these secrets identically and then just
201              * distinguish between them when counting what we saw.
202              */
203             if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
204                 client_handshake_secret_count++;
205             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
206                 server_handshake_secret_count++;
207             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
208                 client_application_secret_count++;
209             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
210                 server_application_secret_count++;
211
212             client_random_size = SSL_get_client_random(ssl,
213                                                        actual_client_random,
214                                                        SSL3_RANDOM_SIZE);
215             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
216                 return 0;
217
218             if (!TEST_ptr(token = strtok(NULL, " \n")))
219                 return 0;
220             if (!TEST_size_t_eq(strlen(token), 64))
221                 return 0;
222             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
223                                                        actual_client_random,
224                                                        client_random_size)))
225                 return 0;
226
227             if (!TEST_ptr(token = strtok(NULL, " \n")))
228                 return 0;
229
230             /*
231              * TODO(TLS1.3): test that application traffic secrets are what
232              * we expect */
233         } else {
234             TEST_info("Unexpected token %s\n", token);
235             return 0;
236         }
237     }
238
239     /* Got what we expected? */
240     if (!TEST_size_t_eq(rsa_key_exchange_count,
241                         expected->rsa_key_exchange_count)
242             || !TEST_size_t_eq(master_secret_count,
243                                expected->master_secret_count)
244             || !TEST_size_t_eq(client_handshake_secret_count,
245                                expected->client_handshake_secret_count)
246             || !TEST_size_t_eq(server_handshake_secret_count,
247                                expected->server_handshake_secret_count)
248             || !TEST_size_t_eq(client_application_secret_count,
249                                expected->client_application_secret_count)
250             || !TEST_size_t_eq(server_application_secret_count,
251                                expected->server_application_secret_count))
252         return 0;
253     return 1;
254 }
255
256 static int test_keylog(void)
257 {
258     SSL_CTX *cctx = NULL, *sctx = NULL;
259     SSL *clientssl = NULL, *serverssl = NULL;
260     int testresult = 0;
261     struct sslapitest_log_counts expected = {0};
262
263     /* Clean up logging space */
264     memset(client_log_buffer, 0, sizeof(client_log_buffer));
265     memset(server_log_buffer, 0, sizeof(server_log_buffer));
266     client_log_buffer_index = 0;
267     server_log_buffer_index = 0;
268     error_writing_log = 0;
269
270     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
271                                        TLS_client_method(),
272                                        &sctx, &cctx, cert, privkey)))
273         return 0;
274
275     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
276     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
277     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
278
279     /* We also want to ensure that we use RSA-based key exchange. */
280     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
281         goto end;
282
283     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
284             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
285         goto end;
286     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
287     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
288                    == client_keylog_callback))
289         goto end;
290     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
291     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
292                    == server_keylog_callback))
293         goto end;
294
295     /* Now do a handshake and check that the logs have been written to. */
296     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
297                                       &clientssl, NULL, NULL))
298             || !TEST_true(create_ssl_connection(serverssl, clientssl,
299                                                 SSL_ERROR_NONE))
300             || !TEST_false(error_writing_log)
301             || !TEST_int_gt(client_log_buffer_index, 0)
302             || !TEST_int_gt(server_log_buffer_index, 0))
303         goto end;
304
305     /*
306      * Now we want to test that our output data was vaguely sensible. We
307      * do that by using strtok and confirming that we have more or less the
308      * data we expect. For both client and server, we expect to see one master
309      * secret. The client should also see a RSA key exchange.
310      */
311     expected.rsa_key_exchange_count = 1;
312     expected.master_secret_count = 1;
313     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
314                                       SSL_get_session(clientssl), &expected)))
315         goto end;
316
317     expected.rsa_key_exchange_count = 0;
318     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
319                                       SSL_get_session(serverssl), &expected)))
320         goto end;
321
322     testresult = 1;
323
324 end:
325     SSL_free(serverssl);
326     SSL_free(clientssl);
327     SSL_CTX_free(sctx);
328     SSL_CTX_free(cctx);
329
330     return testresult;
331 }
332
333 #ifndef OPENSSL_NO_TLS1_3
334 static int test_keylog_no_master_key(void)
335 {
336     SSL_CTX *cctx = NULL, *sctx = NULL;
337     SSL *clientssl = NULL, *serverssl = NULL;
338     int testresult = 0;
339     struct sslapitest_log_counts expected = {0};
340
341     /* Clean up logging space */
342     memset(client_log_buffer, 0, sizeof(client_log_buffer));
343     memset(server_log_buffer, 0, sizeof(server_log_buffer));
344     client_log_buffer_index = 0;
345     server_log_buffer_index = 0;
346     error_writing_log = 0;
347
348     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
349                              TLS_client_method(), &sctx,
350                              &cctx, cert, privkey)))
351         return 0;
352
353     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
354             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
355         goto end;
356
357     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
358     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
359                    == client_keylog_callback))
360         goto end;
361
362     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
363     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
364                    == server_keylog_callback))
365         goto end;
366
367     /* Now do a handshake and check that the logs have been written to. */
368     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
369                                       &clientssl, NULL, NULL))
370             || !TEST_true(create_ssl_connection(serverssl, clientssl,
371                                                 SSL_ERROR_NONE))
372             || !TEST_false(error_writing_log))
373         goto end;
374
375     /*
376      * Now we want to test that our output data was vaguely sensible. For this
377      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
378      * TLSv1.3, but we do expect both client and server to emit keys.
379      */
380     expected.client_handshake_secret_count = 1;
381     expected.server_handshake_secret_count = 1;
382     expected.client_application_secret_count = 1;
383     expected.server_application_secret_count = 1;
384     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
385                                       SSL_get_session(clientssl), &expected))
386             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
387                                              SSL_get_session(serverssl),
388                                              &expected)))
389         goto end;
390
391     testresult = 1;
392
393 end:
394     SSL_free(serverssl);
395     SSL_free(clientssl);
396     SSL_CTX_free(sctx);
397     SSL_CTX_free(cctx);
398
399     return testresult;
400 }
401 #endif
402
403 #ifndef OPENSSL_NO_TLS1_2
404 static int full_early_callback(SSL *s, int *al, void *arg)
405 {
406     int *ctr = arg;
407     const unsigned char *p;
408     int *exts;
409     /* We only configure two ciphers, but the SCSV is added automatically. */
410 #ifdef OPENSSL_NO_EC
411     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0x00, 0xff};
412 #else
413     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
414                                               0x2c, 0x00, 0xff};
415 #endif
416     const int expected_extensions[] = {
417 #ifndef OPENSSL_NO_EC
418                                        11, 10,
419 #endif
420                                        35, 22, 23, 13};
421     size_t len;
422
423     /* Make sure we can defer processing and get called back. */
424     if ((*ctr)++ == 0)
425         return -1;
426
427     len = SSL_early_get0_ciphers(s, &p);
428     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
429             || !TEST_size_t_eq(SSL_early_get0_compression_methods(s, &p), 1)
430             || !TEST_int_eq(*p, 0))
431         return 0;
432     if (!SSL_early_get1_extensions_present(s, &exts, &len))
433         return 0;
434     if (len != OSSL_NELEM(expected_extensions) ||
435         memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
436         printf("Early callback expected ClientHello extensions mismatch\n");
437         OPENSSL_free(exts);
438         return 0;
439     }
440     OPENSSL_free(exts);
441     return 1;
442 }
443
444 static int test_early_cb(void)
445 {
446     SSL_CTX *cctx = NULL, *sctx = NULL;
447     SSL *clientssl = NULL, *serverssl = NULL;
448     int testctr = 0, testresult = 0;
449
450     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
451                                        TLS_client_method(), &sctx,
452                                        &cctx, cert, privkey)))
453         goto end;
454     SSL_CTX_set_early_cb(sctx, full_early_callback, &testctr);
455
456     /* The gimpy cipher list we configure can't do TLS 1.3. */
457     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
458
459     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
460                         "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
461             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
462                                              &clientssl, NULL, NULL))
463             || !TEST_false(create_ssl_connection(serverssl, clientssl,
464                                                  SSL_ERROR_WANT_EARLY))
465                 /*
466                  * Passing a -1 literal is a hack since
467                  * the real value was lost.
468                  * */
469             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_EARLY)
470             || !TEST_true(create_ssl_connection(serverssl, clientssl,
471                                                 SSL_ERROR_NONE)))
472         goto end;
473
474     testresult = 1;
475
476 end:
477     SSL_free(serverssl);
478     SSL_free(clientssl);
479     SSL_CTX_free(sctx);
480     SSL_CTX_free(cctx);
481
482     return testresult;
483 }
484 #endif
485
486 static int execute_test_large_message(const SSL_METHOD *smeth,
487                                       const SSL_METHOD *cmeth, int read_ahead)
488 {
489     SSL_CTX *cctx = NULL, *sctx = NULL;
490     SSL *clientssl = NULL, *serverssl = NULL;
491     int testresult = 0;
492     int i;
493     BIO *certbio = NULL;
494     X509 *chaincert = NULL;
495     int certlen;
496
497     if (!TEST_ptr(certbio = BIO_new_file(cert, "r")))
498         goto end;
499     chaincert = PEM_read_bio_X509(certbio, NULL, NULL, NULL);
500     BIO_free(certbio);
501     certbio = NULL;
502     if (!TEST_ptr(chaincert))
503         goto end;
504
505     if (!TEST_true(create_ssl_ctx_pair(smeth, cmeth, &sctx,
506                                        &cctx, cert, privkey)))
507         goto end;
508
509     if (read_ahead) {
510         /*
511          * Test that read_ahead works correctly when dealing with large
512          * records
513          */
514         SSL_CTX_set_read_ahead(cctx, 1);
515     }
516
517     /*
518      * We assume the supplied certificate is big enough so that if we add
519      * NUM_EXTRA_CERTS it will make the overall message large enough. The
520      * default buffer size is requested to be 16k, but due to the way BUF_MEM
521      * works, it ends up allocating a little over 21k (16 * 4/3). So, in this
522      * test we need to have a message larger than that.
523      */
524     certlen = i2d_X509(chaincert, NULL);
525     OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
526                    (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
527     for (i = 0; i < NUM_EXTRA_CERTS; i++) {
528         if (!X509_up_ref(chaincert))
529             goto end;
530         if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
531             X509_free(chaincert);
532             goto end;
533         }
534     }
535
536     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
537                                       NULL, NULL))
538             || !TEST_true(create_ssl_connection(serverssl, clientssl,
539                                                 SSL_ERROR_NONE)))
540         goto end;
541
542     /*
543      * Calling SSL_clear() first is not required but this tests that SSL_clear()
544      * doesn't leak (when using enable-crypto-mdebug).
545      */
546     if (!TEST_true(SSL_clear(serverssl)))
547         goto end;
548
549     testresult = 1;
550  end:
551     X509_free(chaincert);
552     SSL_free(serverssl);
553     SSL_free(clientssl);
554     SSL_CTX_free(sctx);
555     SSL_CTX_free(cctx);
556
557     return testresult;
558 }
559
560 static int test_large_message_tls(void)
561 {
562     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
563                                       0);
564 }
565
566 static int test_large_message_tls_read_ahead(void)
567 {
568     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
569                                       1);
570 }
571
572 #ifndef OPENSSL_NO_DTLS
573 static int test_large_message_dtls(void)
574 {
575     /*
576      * read_ahead is not relevant to DTLS because DTLS always acts as if
577      * read_ahead is set.
578      */
579     return execute_test_large_message(DTLS_server_method(),
580                                       DTLS_client_method(), 0);
581 }
582 #endif
583
584 #ifndef OPENSSL_NO_OCSP
585 static int ocsp_server_cb(SSL *s, void *arg)
586 {
587     int *argi = (int *)arg;
588     unsigned char *copy = NULL;
589     STACK_OF(OCSP_RESPID) *ids = NULL;
590     OCSP_RESPID *id = NULL;
591
592     if (*argi == 2) {
593         /* In this test we are expecting exactly 1 OCSP_RESPID */
594         SSL_get_tlsext_status_ids(s, &ids);
595         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
596             return SSL_TLSEXT_ERR_ALERT_FATAL;
597
598         id = sk_OCSP_RESPID_value(ids, 0);
599         if (id == NULL || !OCSP_RESPID_match(id, ocspcert))
600             return SSL_TLSEXT_ERR_ALERT_FATAL;
601     } else if (*argi != 1) {
602         return SSL_TLSEXT_ERR_ALERT_FATAL;
603     }
604
605     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
606         return SSL_TLSEXT_ERR_ALERT_FATAL;
607
608     SSL_set_tlsext_status_ocsp_resp(s, copy, sizeof(orespder));
609     ocsp_server_called = 1;
610     return SSL_TLSEXT_ERR_OK;
611 }
612
613 static int ocsp_client_cb(SSL *s, void *arg)
614 {
615     int *argi = (int *)arg;
616     const unsigned char *respderin;
617     size_t len;
618
619     if (*argi != 1 && *argi != 2)
620         return 0;
621
622     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
623     if (!TEST_mem_eq(orespder, len, respderin, len))
624         return 0;
625
626     ocsp_client_called = 1;
627     return 1;
628 }
629
630 static int test_tlsext_status_type(void)
631 {
632     SSL_CTX *cctx = NULL, *sctx = NULL;
633     SSL *clientssl = NULL, *serverssl = NULL;
634     int testresult = 0;
635     STACK_OF(OCSP_RESPID) *ids = NULL;
636     OCSP_RESPID *id = NULL;
637     BIO *certbio = NULL;
638
639     if (!create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(), &sctx,
640                              &cctx, cert, privkey))
641         return 0;
642
643     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
644         goto end;
645
646     /* First just do various checks getting and setting tlsext_status_type */
647
648     clientssl = SSL_new(cctx);
649     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
650             || !TEST_true(SSL_set_tlsext_status_type(clientssl,
651                                                       TLSEXT_STATUSTYPE_ocsp))
652             || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
653                             TLSEXT_STATUSTYPE_ocsp))
654         goto end;
655
656     SSL_free(clientssl);
657     clientssl = NULL;
658
659     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
660      || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
661         goto end;
662
663     clientssl = SSL_new(cctx);
664     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
665         goto end;
666     SSL_free(clientssl);
667     clientssl = NULL;
668
669     /*
670      * Now actually do a handshake and check OCSP information is exchanged and
671      * the callbacks get called
672      */
673     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
674     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
675     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
676     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
677     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
678                                       &clientssl, NULL, NULL))
679             || !TEST_true(create_ssl_connection(serverssl, clientssl,
680                                                 SSL_ERROR_NONE))
681             || !TEST_true(ocsp_client_called)
682             || !TEST_true(ocsp_server_called))
683         goto end;
684     SSL_free(serverssl);
685     SSL_free(clientssl);
686     serverssl = NULL;
687     clientssl = NULL;
688
689     /* Try again but this time force the server side callback to fail */
690     ocsp_client_called = 0;
691     ocsp_server_called = 0;
692     cdummyarg = 0;
693     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
694                                       &clientssl, NULL, NULL))
695                 /* This should fail because the callback will fail */
696             || !TEST_false(create_ssl_connection(serverssl, clientssl,
697                                                  SSL_ERROR_NONE))
698             || !TEST_false(ocsp_client_called)
699             || !TEST_false(ocsp_server_called))
700         goto end;
701     SSL_free(serverssl);
702     SSL_free(clientssl);
703     serverssl = NULL;
704     clientssl = NULL;
705
706     /*
707      * This time we'll get the client to send an OCSP_RESPID that it will
708      * accept.
709      */
710     ocsp_client_called = 0;
711     ocsp_server_called = 0;
712     cdummyarg = 2;
713     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
714                                       &clientssl, NULL, NULL)))
715         goto end;
716
717     /*
718      * We'll just use any old cert for this test - it doesn't have to be an OCSP
719      * specific one. We'll use the server cert.
720      */
721     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
722             || !TEST_ptr(id = OCSP_RESPID_new())
723             || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
724             || !TEST_ptr(ocspcert = PEM_read_bio_X509(certbio,
725                                                       NULL, NULL, NULL))
726             || !TEST_true(OCSP_RESPID_set_by_key(id, ocspcert))
727             || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
728         goto end;
729     id = NULL;
730     SSL_set_tlsext_status_ids(clientssl, ids);
731     /* Control has been transferred */
732     ids = NULL;
733
734     BIO_free(certbio);
735     certbio = NULL;
736
737     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
738                                          SSL_ERROR_NONE))
739             || !TEST_true(ocsp_client_called)
740             || !TEST_true(ocsp_server_called))
741         goto end;
742
743     testresult = 1;
744
745  end:
746     SSL_free(serverssl);
747     SSL_free(clientssl);
748     SSL_CTX_free(sctx);
749     SSL_CTX_free(cctx);
750     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
751     OCSP_RESPID_free(id);
752     BIO_free(certbio);
753     X509_free(ocspcert);
754     ocspcert = NULL;
755
756     return testresult;
757 }
758 #endif
759
760 #if !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
761 static int new_called, remove_called, get_called;
762
763 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
764 {
765     new_called++;
766     /*
767      * sess has been up-refed for us, but we don't actually need it so free it
768      * immediately.
769      */
770     SSL_SESSION_free(sess);
771     return 1;
772 }
773
774 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
775 {
776     remove_called++;
777 }
778
779 static SSL_SESSION *get_sess_val = NULL;
780
781 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
782                                    int *copy)
783 {
784     get_called++;
785     *copy = 1;
786     return get_sess_val;
787 }
788
789 static int execute_test_session(int maxprot, int use_int_cache,
790                                 int use_ext_cache)
791 {
792     SSL_CTX *sctx = NULL, *cctx = NULL;
793     SSL *serverssl1 = NULL, *clientssl1 = NULL;
794     SSL *serverssl2 = NULL, *clientssl2 = NULL;
795 # ifndef OPENSSL_NO_TLS1_1
796     SSL *serverssl3 = NULL, *clientssl3 = NULL;
797 # endif
798     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
799     int testresult = 0;
800
801     new_called = remove_called = 0;
802
803     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
804                                        TLS_client_method(), &sctx,
805                                        &cctx, cert, privkey)))
806         return 0;
807
808     /*
809      * Only allow the max protocol version so we can force a connection failure
810      * later
811      */
812     SSL_CTX_set_min_proto_version(cctx, maxprot);
813     SSL_CTX_set_max_proto_version(cctx, maxprot);
814
815     /* Set up session cache */
816     if (use_ext_cache) {
817         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
818         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
819     }
820     if (use_int_cache) {
821         /* Also covers instance where both are set */
822         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
823     } else {
824         SSL_CTX_set_session_cache_mode(cctx,
825                                        SSL_SESS_CACHE_CLIENT
826                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
827     }
828
829     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
830                                       NULL, NULL))
831             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
832                                                 SSL_ERROR_NONE))
833             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
834         goto end;
835
836     /* Should fail because it should already be in the cache */
837     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
838         goto end;
839     if (use_ext_cache
840             && (!TEST_int_eq(new_called, 1) || !TEST_int_eq(remove_called, 0)))
841         goto end;
842
843     new_called = remove_called = 0;
844     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
845                                       &clientssl2, NULL, NULL))
846             || !TEST_true(SSL_set_session(clientssl2, sess1))
847             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
848                                                 SSL_ERROR_NONE))
849             || !TEST_true(SSL_session_reused(clientssl2)))
850         goto end;
851
852     if (maxprot == TLS1_3_VERSION) {
853         /*
854          * In TLSv1.3 we should have created a new session even though we have
855          * resumed. The original session should also have been removed.
856          */
857         if (use_ext_cache
858                 && (!TEST_int_eq(new_called, 1)
859                     || !TEST_int_eq(remove_called, 1)))
860             goto end;
861     } else {
862         /*
863          * In TLSv1.2 we expect to have resumed so no sessions added or
864          * removed.
865          */
866         if (use_ext_cache
867                 && (!TEST_int_eq(new_called, 0)
868                     || !TEST_int_eq(remove_called, 0)))
869             goto end;
870     }
871
872     SSL_SESSION_free(sess1);
873     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
874         goto end;
875     shutdown_ssl_connection(serverssl2, clientssl2);
876     serverssl2 = clientssl2 = NULL;
877
878     new_called = remove_called = 0;
879     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
880                                       &clientssl2, NULL, NULL))
881             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
882                                                 SSL_ERROR_NONE)))
883         goto end;
884
885     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
886         goto end;
887
888     if (use_ext_cache
889             && (!TEST_int_eq(new_called, 1) || !TEST_int_eq(remove_called, 0)))
890         goto end;
891
892     new_called = remove_called = 0;
893     /*
894      * This should clear sess2 from the cache because it is a "bad" session.
895      * See SSL_set_session() documentation.
896      */
897     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
898         goto end;
899     if (use_ext_cache
900             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
901         goto end;
902     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
903         goto end;
904
905     if (use_int_cache) {
906         /* Should succeeded because it should not already be in the cache */
907         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
908                 || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
909             goto end;
910     }
911
912     new_called = remove_called = 0;
913     /* This shouldn't be in the cache so should fail */
914     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
915         goto end;
916
917     if (use_ext_cache
918             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
919         goto end;
920
921 # if !defined(OPENSSL_NO_TLS1_1)
922     new_called = remove_called = 0;
923     /* Force a connection failure */
924     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
925     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
926                                       &clientssl3, NULL, NULL))
927             || !TEST_true(SSL_set_session(clientssl3, sess1))
928             /* This should fail because of the mismatched protocol versions */
929             || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
930                                                  SSL_ERROR_NONE)))
931         goto end;
932
933     /* We should have automatically removed the session from the cache */
934     if (use_ext_cache
935             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
936         goto end;
937
938     /* Should succeed because it should not already be in the cache */
939     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
940         goto end;
941 # endif
942
943     /* Now do some tests for server side caching */
944     if (use_ext_cache) {
945         SSL_CTX_sess_set_new_cb(cctx, NULL);
946         SSL_CTX_sess_set_remove_cb(cctx, NULL);
947         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
948         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
949         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
950         get_sess_val = NULL;
951     }
952
953     SSL_CTX_set_session_cache_mode(cctx, 0);
954     /* Internal caching is the default on the server side */
955     if (!use_int_cache)
956         SSL_CTX_set_session_cache_mode(sctx,
957                                        SSL_SESS_CACHE_SERVER
958                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
959
960     SSL_free(serverssl1);
961     SSL_free(clientssl1);
962     serverssl1 = clientssl1 = NULL;
963     SSL_free(serverssl2);
964     SSL_free(clientssl2);
965     serverssl2 = clientssl2 = NULL;
966     SSL_SESSION_free(sess1);
967     sess1 = NULL;
968     SSL_SESSION_free(sess2);
969     sess2 = NULL;
970
971     SSL_CTX_set_max_proto_version(sctx, maxprot);
972     SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
973     new_called = remove_called = get_called = 0;
974     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
975                                       NULL, NULL))
976             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
977                                                 SSL_ERROR_NONE))
978             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
979             || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
980         goto end;
981
982     /* Should fail because it should already be in the cache */
983     if (use_int_cache && !TEST_false(SSL_CTX_add_session(sctx, sess2)))
984         goto end;
985
986     if (use_ext_cache) {
987         SSL_SESSION *tmp = sess2;
988
989         if (!TEST_int_eq(new_called, 1)
990                 || !TEST_int_eq(remove_called, 0)
991                 || !TEST_int_eq(get_called, 0))
992             goto end;
993         /*
994          * Delete the session from the internal cache to force a lookup from
995          * the external cache. We take a copy first because
996          * SSL_CTX_remove_session() also marks the session as non-resumable.
997          */
998         if (use_int_cache) {
999             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
1000                     || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
1001                 goto end;
1002             SSL_SESSION_free(sess2);
1003         }
1004         sess2 = tmp;
1005     }
1006
1007     new_called = remove_called = get_called = 0;
1008     get_sess_val = sess2;
1009     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1010                                       &clientssl2, NULL, NULL))
1011             || !TEST_true(SSL_set_session(clientssl2, sess1))
1012             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1013                                                 SSL_ERROR_NONE))
1014             || !TEST_true(SSL_session_reused(clientssl2)))
1015         goto end;
1016
1017     if (use_ext_cache) {
1018         if (!TEST_int_eq(new_called, 0)
1019                 || !TEST_int_eq(remove_called, 0))
1020             goto end;
1021
1022         if (maxprot == TLS1_3_VERSION) {
1023             if (!TEST_int_eq(get_called, 0))
1024                 goto end;
1025         } else {
1026             if (!TEST_int_eq(get_called, 1))
1027                 goto end;
1028         }
1029     }
1030
1031     testresult = 1;
1032
1033  end:
1034     SSL_free(serverssl1);
1035     SSL_free(clientssl1);
1036     SSL_free(serverssl2);
1037     SSL_free(clientssl2);
1038 # ifndef OPENSSL_NO_TLS1_1
1039     SSL_free(serverssl3);
1040     SSL_free(clientssl3);
1041 # endif
1042     SSL_SESSION_free(sess1);
1043     SSL_SESSION_free(sess2);
1044     SSL_CTX_free(sctx);
1045     SSL_CTX_free(cctx);
1046
1047     return testresult;
1048 }
1049 #endif /* !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
1050
1051 static int test_session_with_only_int_cache(void)
1052 {
1053 #ifndef OPENSSL_NO_TLS1_3
1054     if (!execute_test_session(TLS1_3_VERSION, 1, 0))
1055         return 0;
1056 #endif
1057
1058 #ifndef OPENSSL_NO_TLS1_2
1059     return execute_test_session(TLS1_2_VERSION, 1, 0);
1060 #else
1061     return 1;
1062 #endif
1063 }
1064
1065 static int test_session_with_only_ext_cache(void)
1066 {
1067 #ifndef OPENSSL_NO_TLS1_3
1068     if (!execute_test_session(TLS1_3_VERSION, 0, 1))
1069         return 0;
1070 #endif
1071
1072 #ifndef OPENSSL_NO_TLS1_2
1073     return execute_test_session(TLS1_2_VERSION, 0, 1);
1074 #else
1075     return 1;
1076 #endif
1077 }
1078
1079 static int test_session_with_both_cache(void)
1080 {
1081 #ifndef OPENSSL_NO_TLS1_3
1082     if (!execute_test_session(TLS1_3_VERSION, 1, 1))
1083         return 0;
1084 #endif
1085
1086 #ifndef OPENSSL_NO_TLS1_2
1087     return execute_test_session(TLS1_2_VERSION, 1, 1);
1088 #else
1089     return 1;
1090 #endif
1091 }
1092
1093 #define USE_NULL    0
1094 #define USE_BIO_1   1
1095 #define USE_BIO_2   2
1096
1097 #define TOTAL_SSL_SET_BIO_TESTS (3 * 3 * 3 * 3)
1098
1099 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
1100 {
1101     switch (type) {
1102     case USE_NULL:
1103         *res = NULL;
1104         break;
1105     case USE_BIO_1:
1106         *res = bio1;
1107         break;
1108     case USE_BIO_2:
1109         *res = bio2;
1110         break;
1111     }
1112 }
1113
1114 static int test_ssl_set_bio(int idx)
1115 {
1116     SSL_CTX *ctx;
1117     BIO *bio1 = NULL;
1118     BIO *bio2 = NULL;
1119     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
1120     SSL *ssl = NULL;
1121     int initrbio, initwbio, newrbio, newwbio;
1122     int testresult = 0;
1123
1124     initrbio = idx % 3;
1125     idx /= 3;
1126     initwbio = idx % 3;
1127     idx /= 3;
1128     newrbio = idx % 3;
1129     idx /= 3;
1130     newwbio = idx;
1131     if (!TEST_int_le(newwbio, 2))
1132         return 0;
1133
1134     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
1135                 || !TEST_ptr(ssl = SSL_new(ctx)))
1136         goto end;
1137
1138     if (initrbio == USE_BIO_1
1139             || initwbio == USE_BIO_1
1140             || newrbio == USE_BIO_1
1141             || newwbio == USE_BIO_1) {
1142         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
1143             goto end;
1144     }
1145
1146     if (initrbio == USE_BIO_2
1147             || initwbio == USE_BIO_2
1148             || newrbio == USE_BIO_2
1149             || newwbio == USE_BIO_2) {
1150         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
1151             goto end;
1152     }
1153
1154     setupbio(&irbio, bio1, bio2, initrbio);
1155     setupbio(&iwbio, bio1, bio2, initwbio);
1156
1157     /*
1158      * We want to maintain our own refs to these BIO, so do an up ref for each
1159      * BIO that will have ownership transferred in the SSL_set_bio() call
1160      */
1161     if (irbio != NULL)
1162         BIO_up_ref(irbio);
1163     if (iwbio != NULL && iwbio != irbio)
1164         BIO_up_ref(iwbio);
1165
1166     SSL_set_bio(ssl, irbio, iwbio);
1167
1168     setupbio(&nrbio, bio1, bio2, newrbio);
1169     setupbio(&nwbio, bio1, bio2, newwbio);
1170
1171     /*
1172      * We will (maybe) transfer ownership again so do more up refs.
1173      * SSL_set_bio() has some really complicated ownership rules where BIOs have
1174      * already been set!
1175      */
1176     if (nrbio != NULL
1177             && nrbio != irbio
1178             && (nwbio != iwbio || nrbio != nwbio))
1179         BIO_up_ref(nrbio);
1180     if (nwbio != NULL
1181             && nwbio != nrbio
1182             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
1183         BIO_up_ref(nwbio);
1184
1185     SSL_set_bio(ssl, nrbio, nwbio);
1186
1187     testresult = 1;
1188
1189  end:
1190     SSL_free(ssl);
1191     BIO_free(bio1);
1192     BIO_free(bio2);
1193
1194     /*
1195      * This test is checking that the ref counting for SSL_set_bio is correct.
1196      * If we get here and we did too many frees then we will fail in the above
1197      * functions. If we haven't done enough then this will only be detected in
1198      * a crypto-mdebug build
1199      */
1200     SSL_CTX_free(ctx);
1201     return testresult;
1202 }
1203
1204 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
1205
1206 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
1207 {
1208     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
1209     SSL_CTX *ctx;
1210     SSL *ssl = NULL;
1211     int testresult = 0;
1212
1213     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
1214             || !TEST_ptr(ssl = SSL_new(ctx))
1215             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
1216             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
1217         goto end;
1218
1219     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
1220
1221     /*
1222      * If anything goes wrong here then we could leak memory, so this will
1223      * be caught in a crypto-mdebug build
1224      */
1225     BIO_push(sslbio, membio1);
1226
1227     /* Verify changing the rbio/wbio directly does not cause leaks */
1228     if (change_bio != NO_BIO_CHANGE) {
1229         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem())))
1230             goto end;
1231         if (change_bio == CHANGE_RBIO)
1232             SSL_set0_rbio(ssl, membio2);
1233         else
1234             SSL_set0_wbio(ssl, membio2);
1235     }
1236     ssl = NULL;
1237
1238     if (pop_ssl)
1239         BIO_pop(sslbio);
1240     else
1241         BIO_pop(membio1);
1242
1243     testresult = 1;
1244  end:
1245     BIO_free(membio1);
1246     BIO_free(sslbio);
1247     SSL_free(ssl);
1248     SSL_CTX_free(ctx);
1249
1250     return testresult;
1251 }
1252
1253 static int test_ssl_bio_pop_next_bio(void)
1254 {
1255     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
1256 }
1257
1258 static int test_ssl_bio_pop_ssl_bio(void)
1259 {
1260     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
1261 }
1262
1263 static int test_ssl_bio_change_rbio(void)
1264 {
1265     return execute_test_ssl_bio(0, CHANGE_RBIO);
1266 }
1267
1268 static int test_ssl_bio_change_wbio(void)
1269 {
1270     return execute_test_ssl_bio(0, CHANGE_WBIO);
1271 }
1272
1273 typedef struct {
1274     /* The list of sig algs */
1275     const int *list;
1276     /* The length of the list */
1277     size_t listlen;
1278     /* A sigalgs list in string format */
1279     const char *liststr;
1280     /* Whether setting the list should succeed */
1281     int valid;
1282     /* Whether creating a connection with the list should succeed */
1283     int connsuccess;
1284 } sigalgs_list;
1285
1286 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
1287 #ifndef OPENSSL_NO_EC
1288 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
1289 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
1290 #endif
1291 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
1292 static const int invalidlist2[] = {NID_sha256, NID_undef};
1293 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
1294 static const int invalidlist4[] = {NID_sha256};
1295 static const sigalgs_list testsigalgs[] = {
1296     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
1297 #ifndef OPENSSL_NO_EC
1298     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
1299     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
1300 #endif
1301     {NULL, 0, "RSA+SHA256", 1, 1},
1302 #ifndef OPENSSL_NO_EC
1303     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
1304     {NULL, 0, "ECDSA+SHA512", 1, 0},
1305 #endif
1306     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
1307     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
1308     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
1309     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
1310     {NULL, 0, "RSA", 0, 0},
1311     {NULL, 0, "SHA256", 0, 0},
1312     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
1313     {NULL, 0, "Invalid", 0, 0}
1314 };
1315
1316 static int test_set_sigalgs(int idx)
1317 {
1318     SSL_CTX *cctx = NULL, *sctx = NULL;
1319     SSL *clientssl = NULL, *serverssl = NULL;
1320     int testresult = 0;
1321     const sigalgs_list *curr;
1322     int testctx;
1323
1324     /* Should never happen */
1325     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
1326         return 0;
1327
1328     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
1329     curr = testctx ? &testsigalgs[idx]
1330                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
1331
1332     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1333                                        TLS_client_method(), &sctx,
1334                                        &cctx, cert, privkey)))
1335         return 0;
1336
1337     /*
1338      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
1339      * for TLSv1.2 for now until we add a new API.
1340      */
1341     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1342
1343     if (testctx) {
1344         int ret;
1345
1346         if (curr->list != NULL)
1347             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
1348         else
1349             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
1350
1351         if (!ret) {
1352             if (curr->valid)
1353                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
1354             else
1355                 testresult = 1;
1356             goto end;
1357         }
1358         if (!curr->valid) {
1359             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
1360             goto end;
1361         }
1362     }
1363
1364     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1365                                       &clientssl, NULL, NULL)))
1366         goto end;
1367
1368     if (!testctx) {
1369         int ret;
1370
1371         if (curr->list != NULL)
1372             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
1373         else
1374             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
1375         if (!ret) {
1376             if (curr->valid)
1377                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
1378             else
1379                 testresult = 1;
1380             goto end;
1381         }
1382         if (!curr->valid)
1383             goto end;
1384     }
1385
1386     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
1387                                            SSL_ERROR_NONE),
1388                 curr->connsuccess))
1389         goto end;
1390
1391     testresult = 1;
1392
1393  end:
1394     SSL_free(serverssl);
1395     SSL_free(clientssl);
1396     SSL_CTX_free(sctx);
1397     SSL_CTX_free(cctx);
1398
1399     return testresult;
1400 }
1401
1402 #ifndef OPENSSL_NO_TLS1_3
1403
1404 static SSL_SESSION *psk = NULL;
1405 static const char *pskid = "Identity";
1406 static const char *srvid;
1407
1408 static int use_session_cb_cnt = 0;
1409 static int find_session_cb_cnt = 0;
1410
1411 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
1412                           size_t *idlen, SSL_SESSION **sess)
1413 {
1414     switch (++use_session_cb_cnt) {
1415     case 1:
1416         /* The first call should always have a NULL md */
1417         if (md != NULL)
1418             return 0;
1419         break;
1420
1421     case 2:
1422         /* The second call should always have an md */
1423         if (md == NULL)
1424             return 0;
1425         break;
1426
1427     default:
1428         /* We should only be called a maximum of twice */
1429         return 0;
1430     }
1431
1432     if (psk != NULL)
1433         SSL_SESSION_up_ref(psk);
1434
1435     *sess = psk;
1436     *id = (const unsigned char *)pskid;
1437     *idlen = strlen(pskid);
1438
1439     return 1;
1440 }
1441
1442 static int find_session_cb(SSL *ssl, const unsigned char *identity,
1443                            size_t identity_len, SSL_SESSION **sess)
1444 {
1445     find_session_cb_cnt++;
1446
1447     /* We should only ever be called a maximum of twice per connection */
1448     if (find_session_cb_cnt > 2)
1449         return 0;
1450
1451     if (psk == NULL)
1452         return 0;
1453
1454     /* Identity should match that set by the client */
1455     if (strlen(srvid) != identity_len
1456             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
1457         /* No PSK found, continue but without a PSK */
1458         *sess = NULL;
1459         return 1;
1460     }
1461
1462     SSL_SESSION_up_ref(psk);
1463     *sess = psk;
1464
1465     return 1;
1466 }
1467
1468 #define MSG1    "Hello"
1469 #define MSG2    "World."
1470 #define MSG3    "This"
1471 #define MSG4    "is"
1472 #define MSG5    "a"
1473 #define MSG6    "test"
1474 #define MSG7    "message."
1475
1476 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
1477
1478 /*
1479  * Helper method to setup objects for early data test. Caller frees objects on
1480  * error.
1481  */
1482 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
1483                                 SSL **serverssl, SSL_SESSION **sess, int idx)
1484 {
1485     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1486                                        TLS_client_method(), sctx,
1487                                        cctx, cert, privkey)))
1488         return 0;
1489
1490     if (idx == 1) {
1491         /* When idx == 1 we repeat the tests with read_ahead set */
1492         SSL_CTX_set_read_ahead(*cctx, 1);
1493         SSL_CTX_set_read_ahead(*sctx, 1);
1494     } else if (idx == 2) {
1495         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
1496         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
1497         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
1498         use_session_cb_cnt = 0;
1499         find_session_cb_cnt = 0;
1500         srvid = pskid;
1501     }
1502
1503     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
1504                                       NULL, NULL)))
1505         return 0;
1506
1507     if (idx == 2) {
1508         /* Create the PSK */
1509         const SSL_CIPHER *cipher = NULL;
1510         const unsigned char key[] = {
1511             0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
1512             0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
1513             0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
1514             0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
1515             0x2c, 0x2d, 0x2e, 0x2f
1516         };
1517
1518         cipher = SSL_CIPHER_find(*clientssl, TLS13_AES_256_GCM_SHA384_BYTES);
1519         psk = SSL_SESSION_new();
1520         if (!TEST_ptr(psk)
1521                 || !TEST_ptr(cipher)
1522                 || !TEST_true(SSL_SESSION_set1_master_key(psk, key,
1523                                                           sizeof(key)))
1524                 || !TEST_true(SSL_SESSION_set_cipher(psk, cipher))
1525                 || !TEST_true(
1526                         SSL_SESSION_set_protocol_version(psk,
1527                                                          TLS1_3_VERSION))
1528                    /*
1529                     * We just choose an arbitrary value for max_early_data which
1530                     * should be big enough for testing purposes.
1531                     */
1532                 || !TEST_true(SSL_SESSION_set_max_early_data(psk, 0x100))) {
1533             SSL_SESSION_free(psk);
1534             psk = NULL;
1535             return 0;
1536         }
1537
1538         if (sess != NULL)
1539             *sess = psk;
1540         return 1;
1541     }
1542
1543     if (sess == NULL)
1544         return 1;
1545
1546     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
1547                                          SSL_ERROR_NONE)))
1548         return 0;
1549
1550     *sess = SSL_get1_session(*clientssl);
1551     SSL_shutdown(*clientssl);
1552     SSL_shutdown(*serverssl);
1553     SSL_free(*serverssl);
1554     SSL_free(*clientssl);
1555     *serverssl = *clientssl = NULL;
1556
1557     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
1558                                       clientssl, NULL, NULL))
1559             || !TEST_true(SSL_set_session(*clientssl, *sess)))
1560         return 0;
1561
1562     return 1;
1563 }
1564
1565 static int test_early_data_read_write(int idx)
1566 {
1567     SSL_CTX *cctx = NULL, *sctx = NULL;
1568     SSL *clientssl = NULL, *serverssl = NULL;
1569     int testresult = 0;
1570     SSL_SESSION *sess = NULL;
1571     unsigned char buf[20], data[1024];
1572     size_t readbytes, written, eoedlen, rawread, rawwritten;
1573     BIO *rbio;
1574
1575     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1576                                         &serverssl, &sess, idx)))
1577         goto end;
1578
1579     /* Write and read some early data */
1580     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1581                                         &written))
1582             || !TEST_size_t_eq(written, strlen(MSG1))
1583             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
1584                                                 sizeof(buf), &readbytes),
1585                             SSL_READ_EARLY_DATA_SUCCESS)
1586             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
1587             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1588                             SSL_EARLY_DATA_ACCEPTED))
1589         goto end;
1590
1591     /*
1592      * Server should be able to write data, and client should be able to
1593      * read it.
1594      */
1595     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
1596                                         &written))
1597             || !TEST_size_t_eq(written, strlen(MSG2))
1598             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1599             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1600         goto end;
1601
1602     /* Even after reading normal data, client should be able write early data */
1603     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
1604                                         &written))
1605             || !TEST_size_t_eq(written, strlen(MSG3)))
1606         goto end;
1607
1608     /* Server should still be able read early data after writing data */
1609     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1610                                          &readbytes),
1611                      SSL_READ_EARLY_DATA_SUCCESS)
1612             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
1613         goto end;
1614
1615     /* Write more data from server and read it from client */
1616     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
1617                                         &written))
1618             || !TEST_size_t_eq(written, strlen(MSG4))
1619             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1620             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
1621         goto end;
1622
1623     /*
1624      * If client writes normal data it should mean writing early data is no
1625      * longer possible.
1626      */
1627     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
1628             || !TEST_size_t_eq(written, strlen(MSG5))
1629             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1630                             SSL_EARLY_DATA_ACCEPTED))
1631         goto end;
1632
1633     /*
1634      * At this point the client has written EndOfEarlyData, ClientFinished and
1635      * normal (fully protected) data. We are going to cause a delay between the
1636      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
1637      * in the read BIO, and then just put back the EndOfEarlyData message.
1638      */
1639     rbio = SSL_get_rbio(serverssl);
1640     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
1641             || !TEST_size_t_lt(rawread, sizeof(data))
1642             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
1643         goto end;
1644
1645     /* Record length is in the 4th and 5th bytes of the record header */
1646     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
1647     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
1648             || !TEST_size_t_eq(rawwritten, eoedlen))
1649         goto end;
1650
1651     /* Server should be told that there is no more early data */
1652     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1653                                          &readbytes),
1654                      SSL_READ_EARLY_DATA_FINISH)
1655             || !TEST_size_t_eq(readbytes, 0))
1656         goto end;
1657
1658     /*
1659      * Server has not finished init yet, so should still be able to write early
1660      * data.
1661      */
1662     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
1663                                         &written))
1664             || !TEST_size_t_eq(written, strlen(MSG6)))
1665         goto end;
1666
1667     /* Push the ClientFinished and the normal data back into the server rbio */
1668     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
1669                                 &rawwritten))
1670             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
1671         goto end;
1672
1673     /* Server should be able to read normal data */
1674     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1675             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
1676         goto end;
1677
1678     /* Client and server should not be able to write/read early data now */
1679     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
1680                                          &written)))
1681         goto end;
1682     ERR_clear_error();
1683     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1684                                          &readbytes),
1685                      SSL_READ_EARLY_DATA_ERROR))
1686         goto end;
1687     ERR_clear_error();
1688
1689     /* Client should be able to read the data sent by the server */
1690     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1691             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
1692         goto end;
1693
1694     /*
1695      * Make sure we process the NewSessionTicket. This arrives post-handshake.
1696      * We attempt a read which we do not expect to return any data.
1697      */
1698     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)))
1699         goto end;
1700
1701     /* Server should be able to write normal data */
1702     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
1703             || !TEST_size_t_eq(written, strlen(MSG7))
1704             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1705             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
1706         goto end;
1707
1708     /* We keep the PSK session around if using PSK */
1709     if (idx != 2)
1710         SSL_SESSION_free(sess);
1711     sess = SSL_get1_session(clientssl);
1712     use_session_cb_cnt = 0;
1713     find_session_cb_cnt = 0;
1714
1715     SSL_shutdown(clientssl);
1716     SSL_shutdown(serverssl);
1717     SSL_free(serverssl);
1718     SSL_free(clientssl);
1719     serverssl = clientssl = NULL;
1720     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1721                                       &clientssl, NULL, NULL))
1722             || !TEST_true(SSL_set_session(clientssl, sess)))
1723         goto end;
1724
1725     /* Write and read some early data */
1726     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1727                                         &written))
1728             || !TEST_size_t_eq(written, strlen(MSG1))
1729             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1730                                                 &readbytes),
1731                             SSL_READ_EARLY_DATA_SUCCESS)
1732             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
1733         goto end;
1734
1735     if (!TEST_int_gt(SSL_connect(clientssl), 0)
1736             || !TEST_int_gt(SSL_accept(serverssl), 0))
1737         goto end;
1738
1739     /* Client and server should not be able to write/read early data now */
1740     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
1741                                          &written)))
1742         goto end;
1743     ERR_clear_error();
1744     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1745                                          &readbytes),
1746                      SSL_READ_EARLY_DATA_ERROR))
1747         goto end;
1748     ERR_clear_error();
1749
1750     /* Client and server should be able to write/read normal data */
1751     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
1752             || !TEST_size_t_eq(written, strlen(MSG5))
1753             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1754             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
1755         goto end;
1756
1757     testresult = 1;
1758
1759  end:
1760     SSL_SESSION_free(sess);
1761     psk = NULL;
1762     SSL_free(serverssl);
1763     SSL_free(clientssl);
1764     SSL_CTX_free(sctx);
1765     SSL_CTX_free(cctx);
1766     return testresult;
1767 }
1768
1769 /*
1770  * Helper function to test that a server attempting to read early data can
1771  * handle a connection from a client where the early data should be skipped.
1772  */
1773 static int early_data_skip_helper(int hrr, int idx)
1774 {
1775     SSL_CTX *cctx = NULL, *sctx = NULL;
1776     SSL *clientssl = NULL, *serverssl = NULL;
1777     int testresult = 0;
1778     SSL_SESSION *sess = NULL;
1779     unsigned char buf[20];
1780     size_t readbytes, written;
1781
1782     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1783                                         &serverssl, &sess, idx)))
1784         goto end;
1785
1786     if (hrr) {
1787         /* Force an HRR to occur */
1788         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
1789             goto end;
1790     } else if (idx == 2) {
1791         /*
1792          * We force early_data rejection by ensuring the PSK identity is
1793          * unrecognised
1794          */
1795         srvid = "Dummy Identity";
1796     } else {
1797         /*
1798          * Deliberately corrupt the creation time. We take 20 seconds off the
1799          * time. It could be any value as long as it is not within tolerance.
1800          * This should mean the ticket is rejected.
1801          */
1802         if (!TEST_true(SSL_SESSION_set_time(sess, time(NULL) - 20)))
1803             goto end;
1804     }
1805
1806     /* Write some early data */
1807     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1808                                         &written))
1809             || !TEST_size_t_eq(written, strlen(MSG1)))
1810         goto end;
1811
1812     /* Server should reject the early data and skip over it */
1813     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1814                                          &readbytes),
1815                      SSL_READ_EARLY_DATA_FINISH)
1816             || !TEST_size_t_eq(readbytes, 0)
1817             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1818                             SSL_EARLY_DATA_REJECTED))
1819         goto end;
1820
1821     if (hrr) {
1822         /*
1823          * Finish off the handshake. We perform the same writes and reads as
1824          * further down but we expect them to fail due to the incomplete
1825          * handshake.
1826          */
1827         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
1828                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
1829                                &readbytes)))
1830             goto end;
1831     }
1832
1833     /* Should be able to send normal data despite rejection of early data */
1834     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
1835             || !TEST_size_t_eq(written, strlen(MSG2))
1836             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1837                             SSL_EARLY_DATA_REJECTED)
1838             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1839             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1840         goto end;
1841
1842     testresult = 1;
1843
1844  end:
1845     if (sess != psk)
1846         SSL_SESSION_free(psk);
1847     psk = NULL;
1848     SSL_SESSION_free(sess);
1849     SSL_free(serverssl);
1850     SSL_free(clientssl);
1851     SSL_CTX_free(sctx);
1852     SSL_CTX_free(cctx);
1853     return testresult;
1854 }
1855
1856 /*
1857  * Test that a server attempting to read early data can handle a connection
1858  * from a client where the early data is not acceptable.
1859  */
1860 static int test_early_data_skip(int idx)
1861 {
1862     return early_data_skip_helper(0, idx);
1863 }
1864
1865 /*
1866  * Test that a server attempting to read early data can handle a connection
1867  * from a client where an HRR occurs.
1868  */
1869 static int test_early_data_skip_hrr(int idx)
1870 {
1871     return early_data_skip_helper(1, idx);
1872 }
1873
1874 /*
1875  * Test that a server attempting to read early data can handle a connection
1876  * from a client that doesn't send any.
1877  */
1878 static int test_early_data_not_sent(int idx)
1879 {
1880     SSL_CTX *cctx = NULL, *sctx = NULL;
1881     SSL *clientssl = NULL, *serverssl = NULL;
1882     int testresult = 0;
1883     SSL_SESSION *sess = NULL;
1884     unsigned char buf[20];
1885     size_t readbytes, written;
1886
1887     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1888                                         &serverssl, &sess, idx)))
1889         goto end;
1890
1891     /* Write some data - should block due to handshake with server */
1892     SSL_set_connect_state(clientssl);
1893     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
1894         goto end;
1895
1896     /* Server should detect that early data has not been sent */
1897     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1898                                          &readbytes),
1899                      SSL_READ_EARLY_DATA_FINISH)
1900             || !TEST_size_t_eq(readbytes, 0)
1901             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1902                             SSL_EARLY_DATA_NOT_SENT)
1903             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1904                             SSL_EARLY_DATA_NOT_SENT))
1905         goto end;
1906
1907     /* Continue writing the message we started earlier */
1908     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
1909             || !TEST_size_t_eq(written, strlen(MSG1))
1910             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1911             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
1912             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
1913             || !TEST_size_t_eq(written, strlen(MSG2)))
1914         goto end;
1915
1916     /*
1917      * Should block due to the NewSessionTicket arrival unless we're using
1918      * read_ahead
1919      */
1920     if (idx != 1) {
1921         if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)))
1922             goto end;
1923     }
1924
1925     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1926             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1927         goto end;
1928
1929     testresult = 1;
1930
1931  end:
1932     SSL_SESSION_free(sess);
1933     psk = NULL;
1934     SSL_free(serverssl);
1935     SSL_free(clientssl);
1936     SSL_CTX_free(sctx);
1937     SSL_CTX_free(cctx);
1938     return testresult;
1939 }
1940
1941 static const char *servhostname;
1942
1943 static int hostname_cb(SSL *s, int *al, void *arg)
1944 {
1945     const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1946
1947     if (hostname != NULL && strcmp(hostname, servhostname) == 0)
1948         return  SSL_TLSEXT_ERR_OK;
1949
1950     return SSL_TLSEXT_ERR_NOACK;
1951 }
1952
1953 static const char *servalpn;
1954
1955 static int alpn_select_cb (SSL *ssl, const unsigned char **out, unsigned char *outlen,
1956                     const unsigned char *in, unsigned int inlen, void *arg)
1957 {
1958     unsigned int i, protlen = 0;
1959     const unsigned char *prot;
1960
1961     for (i = 0, prot = in; i < inlen; i += protlen, prot += protlen) {
1962         protlen = *(prot++);
1963         if (inlen - i < protlen)
1964             return SSL_TLSEXT_ERR_NOACK;
1965
1966         if (protlen == strlen(servalpn)
1967                 && memcmp(prot, "goodalpn", protlen) == 0) {
1968             *out = prot;
1969             *outlen = protlen;
1970             return SSL_TLSEXT_ERR_OK;
1971         }
1972     }
1973
1974     return SSL_TLSEXT_ERR_NOACK;
1975 }
1976
1977 static int test_early_data_psk(int idx)
1978 {
1979     SSL_CTX *cctx = NULL, *sctx = NULL;
1980     SSL *clientssl = NULL, *serverssl = NULL;
1981     int testresult = 0;
1982     SSL_SESSION *sess = NULL;
1983     unsigned char badalpn[] = { 0x07, 'b', 'a', 'd', 'a', 'l', 'p', 'n' };
1984     unsigned char goodalpn[] = { 0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n' };
1985     int err;
1986     unsigned char buf[20];
1987     size_t readbytes, written;
1988     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
1989     int edstatus = SSL_EARLY_DATA_ACCEPTED;
1990
1991     /* We always set this up with a final parameter of "2" for PSK */
1992     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1993                                         &serverssl, &sess, 2)))
1994         goto end;
1995
1996     servhostname = "goodhost";
1997     servalpn = "goodalpn";
1998
1999     switch (idx) {
2000     case 0:
2001         /* Set inconsistent SNI (client detected) */
2002         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
2003         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2004                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
2005             goto end;
2006         break;
2007
2008     case 1:
2009         /* Set inconsistent ALPN (client detected) */
2010         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
2011         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
2012         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, goodalpn,
2013                                                       sizeof(goodalpn)))
2014                 || !TEST_false(SSL_set_alpn_protos(clientssl, badalpn,
2015                                                    sizeof(badalpn))))
2016             goto end;
2017         break;
2018
2019     case 2:
2020         /*
2021          * Set invalid protocol version. Technically this affects PSKs without
2022          * early_data too, but we test it here because it is similar to the
2023          * SNI/ALPN consistency tests.
2024          */
2025         err = SSL_R_BAD_PSK;
2026         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
2027             goto end;
2028         break;
2029
2030     case 3:
2031         /*
2032          * Set inconsistent SNI (server detected). In this case the connection
2033          * will succeed but reject early_data.
2034          */
2035         servhostname = "badhost";
2036         edstatus = SSL_EARLY_DATA_REJECTED;
2037         readearlyres = SSL_READ_EARLY_DATA_FINISH;
2038         /* Fall through */
2039     case 4:
2040         /* Set consistent SNI */
2041         err = 0;
2042         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2043                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
2044                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
2045                                 hostname_cb)))
2046             goto end;
2047         break;
2048
2049     case 5:
2050         /*
2051          * Set inconsistent ALPN (server detected). In this case the connection
2052          * will succeed but reject early_data.
2053          */
2054         servalpn = "badalpn";
2055         edstatus = SSL_EARLY_DATA_REJECTED;
2056         readearlyres = SSL_READ_EARLY_DATA_FINISH;
2057         /* Fall through */
2058     case 6:
2059         /* Set consistent ALPN */
2060         err = 0;
2061         /*
2062          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
2063          * accepts a list of protos (each one length prefixed).
2064          * SSL_set1_alpn_selected accepts a single protocol (not length
2065          * prefixed)
2066          */
2067         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, goodalpn + 1,
2068                                                       sizeof(goodalpn) - 1))
2069                 || !TEST_false(SSL_set_alpn_protos(clientssl, goodalpn,
2070                                                    sizeof(goodalpn))))
2071             goto end;
2072
2073         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
2074         break;
2075
2076     default:
2077         TEST_error("Bad test index");
2078         goto end;
2079     }
2080
2081     SSL_set_connect_state(clientssl);
2082     if (err != 0) {
2083         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2084                                             &written))
2085                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
2086                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
2087             goto end;
2088     } else {
2089         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2090                                             &written))
2091                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2092                                                   &readbytes), readearlyres)
2093                 || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
2094                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
2095                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus))
2096             goto end;
2097     }
2098
2099     testresult = 1;
2100
2101  end:
2102     SSL_SESSION_free(sess);
2103     psk = NULL;
2104     SSL_free(serverssl);
2105     SSL_free(clientssl);
2106     SSL_CTX_free(sctx);
2107     SSL_CTX_free(cctx);
2108     return testresult;
2109 }
2110
2111 /*
2112  * Test that a server that doesn't try to read early data can handle a
2113  * client sending some.
2114  */
2115 static int test_early_data_not_expected(int idx)
2116 {
2117     SSL_CTX *cctx = NULL, *sctx = NULL;
2118     SSL *clientssl = NULL, *serverssl = NULL;
2119     int testresult = 0;
2120     SSL_SESSION *sess = NULL;
2121     unsigned char buf[20];
2122     size_t readbytes, written;
2123
2124     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2125                                         &serverssl, &sess, idx)))
2126         goto end;
2127
2128     /* Write some early data */
2129     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2130                                         &written)))
2131         goto end;
2132
2133     /*
2134      * Server should skip over early data and then block waiting for client to
2135      * continue handshake
2136      */
2137     if (!TEST_int_le(SSL_accept(serverssl), 0)
2138      || !TEST_int_gt(SSL_connect(clientssl), 0)
2139      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2140                      SSL_EARLY_DATA_REJECTED)
2141      || !TEST_int_gt(SSL_accept(serverssl), 0)
2142      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2143                      SSL_EARLY_DATA_REJECTED))
2144         goto end;
2145
2146     /* Send some normal data from client to server */
2147     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2148             || !TEST_size_t_eq(written, strlen(MSG2)))
2149         goto end;
2150
2151     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2152             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2153         goto end;
2154
2155     testresult = 1;
2156
2157  end:
2158     SSL_SESSION_free(sess);
2159     psk = NULL;
2160     SSL_free(serverssl);
2161     SSL_free(clientssl);
2162     SSL_CTX_free(sctx);
2163     SSL_CTX_free(cctx);
2164     return testresult;
2165 }
2166
2167
2168 # ifndef OPENSSL_NO_TLS1_2
2169 /*
2170  * Test that a server attempting to read early data can handle a connection
2171  * from a TLSv1.2 client.
2172  */
2173 static int test_early_data_tls1_2(int idx)
2174 {
2175     SSL_CTX *cctx = NULL, *sctx = NULL;
2176     SSL *clientssl = NULL, *serverssl = NULL;
2177     int testresult = 0;
2178     unsigned char buf[20];
2179     size_t readbytes, written;
2180
2181     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2182                                         &serverssl, NULL, idx)))
2183         goto end;
2184
2185     /* Write some data - should block due to handshake with server */
2186     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
2187     SSL_set_connect_state(clientssl);
2188     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
2189         goto end;
2190
2191     /*
2192      * Server should do TLSv1.2 handshake. First it will block waiting for more
2193      * messages from client after ServerDone. Then SSL_read_early_data should
2194      * finish and detect that early data has not been sent
2195      */
2196     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2197                                          &readbytes),
2198                      SSL_READ_EARLY_DATA_ERROR))
2199         goto end;
2200
2201     /*
2202      * Continue writing the message we started earlier. Will still block waiting
2203      * for the CCS/Finished from server
2204      */
2205     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2206             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2207                                                 &readbytes),
2208                             SSL_READ_EARLY_DATA_FINISH)
2209             || !TEST_size_t_eq(readbytes, 0)
2210             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2211                             SSL_EARLY_DATA_NOT_SENT))
2212         goto end;
2213
2214     /* Continue writing the message we started earlier */
2215     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2216             || !TEST_size_t_eq(written, strlen(MSG1))
2217             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2218                             SSL_EARLY_DATA_NOT_SENT)
2219             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2220             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
2221             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
2222             || !TEST_size_t_eq(written, strlen(MSG2))
2223             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
2224             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2225         goto end;
2226
2227     testresult = 1;
2228
2229  end:
2230     SSL_SESSION_free(psk);
2231     psk = NULL;
2232     SSL_free(serverssl);
2233     SSL_free(clientssl);
2234     SSL_CTX_free(sctx);
2235     SSL_CTX_free(cctx);
2236
2237     return testresult;
2238 }
2239 # endif /* OPENSSL_NO_TLS1_2 */
2240
2241 static int test_ciphersuite_change(void)
2242 {
2243     SSL_CTX *cctx = NULL, *sctx = NULL;
2244     SSL *clientssl = NULL, *serverssl = NULL;
2245     SSL_SESSION *clntsess = NULL;
2246     int testresult = 0;
2247     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
2248
2249     /* Create a session based on SHA-256 */
2250     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2251                                        TLS_client_method(), &sctx,
2252                                        &cctx, cert, privkey))
2253             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
2254                                                   "TLS13-AES-128-GCM-SHA256"))
2255             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2256                                           &clientssl, NULL, NULL))
2257             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2258                                                 SSL_ERROR_NONE)))
2259         goto end;
2260
2261     clntsess = SSL_get1_session(clientssl);
2262     /* Save for later */
2263     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
2264     SSL_shutdown(clientssl);
2265     SSL_shutdown(serverssl);
2266     SSL_free(serverssl);
2267     SSL_free(clientssl);
2268     serverssl = clientssl = NULL;
2269
2270     /* Check we can resume a session with a different SHA-256 ciphersuite */
2271     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
2272                                            "TLS13-CHACHA20-POLY1305-SHA256"))
2273             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2274                                              NULL, NULL))
2275             || !TEST_true(SSL_set_session(clientssl, clntsess))
2276             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2277                                                 SSL_ERROR_NONE))
2278             || !TEST_true(SSL_session_reused(clientssl)))
2279         goto end;
2280
2281     SSL_SESSION_free(clntsess);
2282     clntsess = SSL_get1_session(clientssl);
2283     SSL_shutdown(clientssl);
2284     SSL_shutdown(serverssl);
2285     SSL_free(serverssl);
2286     SSL_free(clientssl);
2287     serverssl = clientssl = NULL;
2288
2289     /*
2290      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
2291      * succeeds but does not resume.
2292      */
2293     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "TLS13-AES-256-GCM-SHA384"))
2294             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2295                                              NULL, NULL))
2296             || !TEST_true(SSL_set_session(clientssl, clntsess))
2297             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2298                                                 SSL_ERROR_SSL))
2299             || !TEST_false(SSL_session_reused(clientssl)))
2300         goto end;
2301
2302     SSL_SESSION_free(clntsess);
2303     clntsess = NULL;
2304     SSL_shutdown(clientssl);
2305     SSL_shutdown(serverssl);
2306     SSL_free(serverssl);
2307     SSL_free(clientssl);
2308     serverssl = clientssl = NULL;
2309
2310     /* Create a session based on SHA384 */
2311     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "TLS13-AES-256-GCM-SHA384"))
2312             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2313                                           &clientssl, NULL, NULL))
2314             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2315                                                 SSL_ERROR_NONE)))
2316         goto end;
2317
2318     clntsess = SSL_get1_session(clientssl);
2319     SSL_shutdown(clientssl);
2320     SSL_shutdown(serverssl);
2321     SSL_free(serverssl);
2322     SSL_free(clientssl);
2323     serverssl = clientssl = NULL;
2324
2325     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
2326                    "TLS13-AES-128-GCM-SHA256:TLS13-AES-256-GCM-SHA384"))
2327             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
2328                                                   "TLS13-AES-256-GCM-SHA384"))
2329             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2330                                              NULL, NULL))
2331             || !TEST_true(SSL_set_session(clientssl, clntsess))
2332                /*
2333                 * We use SSL_ERROR_WANT_READ below so that we can pause the
2334                 * connection after the initial ClientHello has been sent to
2335                 * enable us to make some session changes.
2336                 */
2337             || !TEST_false(create_ssl_connection(serverssl, clientssl,
2338                                                 SSL_ERROR_WANT_READ)))
2339         goto end;
2340
2341     /* Trick the client into thinking this session is for a different digest */
2342     clntsess->cipher = aes_128_gcm_sha256;
2343     clntsess->cipher_id = clntsess->cipher->id;
2344
2345     /*
2346      * Continue the previously started connection. Server has selected a SHA-384
2347      * ciphersuite, but client thinks the session is for SHA-256, so it should
2348      * bail out.
2349      */
2350     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
2351                                                 SSL_ERROR_SSL))
2352             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
2353                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
2354         goto end;
2355
2356     testresult = 1;
2357
2358  end:
2359     SSL_SESSION_free(clntsess);
2360     SSL_free(serverssl);
2361     SSL_free(clientssl);
2362     SSL_CTX_free(sctx);
2363     SSL_CTX_free(cctx);
2364
2365     return testresult;
2366 }
2367
2368 static int test_tls13_psk(void)
2369 {
2370     SSL_CTX *sctx = NULL, *cctx = NULL;
2371     SSL *serverssl = NULL, *clientssl = NULL;
2372     const SSL_CIPHER *cipher = NULL;
2373     const unsigned char key[] = {
2374         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
2375         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
2376         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
2377         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
2378     };
2379     int testresult = 0;
2380
2381     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2382                                        TLS_client_method(), &sctx,
2383                                        &cctx, cert, privkey)))
2384         goto end;
2385
2386     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2387     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2388     srvid = pskid;
2389     use_session_cb_cnt = 0;
2390     find_session_cb_cnt = 0;
2391
2392     /* Check we can create a connection if callback decides not to send a PSK */
2393     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2394                                              NULL, NULL))
2395             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2396                                                 SSL_ERROR_NONE))
2397             || !TEST_false(SSL_session_reused(clientssl))
2398             || !TEST_false(SSL_session_reused(serverssl))
2399             || !TEST_true(use_session_cb_cnt == 1)
2400             || !TEST_true(find_session_cb_cnt == 0))
2401         goto end;
2402
2403     shutdown_ssl_connection(serverssl, clientssl);
2404     serverssl = clientssl = NULL;
2405     use_session_cb_cnt = 0;
2406
2407     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2408                                              NULL, NULL)))
2409         goto end;
2410
2411     /* Create the PSK */
2412     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_256_GCM_SHA384_BYTES);
2413     psk = SSL_SESSION_new();
2414     if (!TEST_ptr(psk)
2415             || !TEST_ptr(cipher)
2416             || !TEST_true(SSL_SESSION_set1_master_key(psk, key, sizeof(key)))
2417             || !TEST_true(SSL_SESSION_set_cipher(psk, cipher))
2418             || !TEST_true(SSL_SESSION_set_protocol_version(psk,
2419                                                            TLS1_3_VERSION)))
2420         goto end;
2421
2422     /* Check we can create a connection and the PSK is used */
2423     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2424             || !TEST_true(SSL_session_reused(clientssl))
2425             || !TEST_true(SSL_session_reused(serverssl))
2426             || !TEST_true(use_session_cb_cnt == 1)
2427             || !TEST_true(find_session_cb_cnt == 1))
2428         goto end;
2429
2430     shutdown_ssl_connection(serverssl, clientssl);
2431     serverssl = clientssl = NULL;
2432     use_session_cb_cnt = find_session_cb_cnt = 0;
2433
2434     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2435                                              NULL, NULL)))
2436         goto end;
2437
2438     /* Force an HRR */
2439     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2440         goto end;
2441
2442     /*
2443      * Check we can create a connection, the PSK is used and the callbacks are
2444      * called twice.
2445      */
2446     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2447             || !TEST_true(SSL_session_reused(clientssl))
2448             || !TEST_true(SSL_session_reused(serverssl))
2449             || !TEST_true(use_session_cb_cnt == 2)
2450             || !TEST_true(find_session_cb_cnt == 2))
2451         goto end;
2452
2453     shutdown_ssl_connection(serverssl, clientssl);
2454     serverssl = clientssl = NULL;
2455     use_session_cb_cnt = find_session_cb_cnt = 0;
2456
2457     /*
2458      * Check that if the server rejects the PSK we can still connect, but with
2459      * a full handshake
2460      */
2461     srvid = "Dummy Identity";
2462     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2463                                              NULL, NULL))
2464             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2465                                                 SSL_ERROR_NONE))
2466             || !TEST_false(SSL_session_reused(clientssl))
2467             || !TEST_false(SSL_session_reused(serverssl))
2468             || !TEST_true(use_session_cb_cnt == 1)
2469             || !TEST_true(find_session_cb_cnt == 1))
2470         goto end;
2471
2472     shutdown_ssl_connection(serverssl, clientssl);
2473     serverssl = clientssl = NULL;
2474     testresult = 1;
2475
2476  end:
2477     SSL_SESSION_free(psk);
2478     SSL_free(serverssl);
2479     SSL_free(clientssl);
2480     SSL_CTX_free(sctx);
2481     SSL_CTX_free(cctx);
2482     return testresult;
2483 }
2484
2485 #endif /* OPENSSL_NO_TLS1_3 */
2486
2487 static int clntaddoldcb = 0;
2488 static int clntparseoldcb = 0;
2489 static int srvaddoldcb = 0;
2490 static int srvparseoldcb = 0;
2491 static int clntaddnewcb = 0;
2492 static int clntparsenewcb = 0;
2493 static int srvaddnewcb = 0;
2494 static int srvparsenewcb = 0;
2495 static int snicb = 0;
2496
2497 #define TEST_EXT_TYPE1  0xff00
2498
2499 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
2500                       size_t *outlen, int *al, void *add_arg)
2501 {
2502     int *server = (int *)add_arg;
2503     unsigned char *data;
2504
2505     if (SSL_is_server(s))
2506         srvaddoldcb++;
2507     else
2508         clntaddoldcb++;
2509
2510     if (*server != SSL_is_server(s)
2511             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
2512         return -1;
2513
2514     *data = 1;
2515     *out = data;
2516     *outlen = sizeof(char);
2517     return 1;
2518 }
2519
2520 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
2521                         void *add_arg)
2522 {
2523     OPENSSL_free((unsigned char *)out);
2524 }
2525
2526 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
2527                         size_t inlen, int *al, void *parse_arg)
2528 {
2529     int *server = (int *)parse_arg;
2530
2531     if (SSL_is_server(s))
2532         srvparseoldcb++;
2533     else
2534         clntparseoldcb++;
2535
2536     if (*server != SSL_is_server(s)
2537             || inlen != sizeof(char)
2538             || *in != 1)
2539         return -1;
2540
2541     return 1;
2542 }
2543
2544 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
2545                       const unsigned char **out, size_t *outlen, X509 *x,
2546                       size_t chainidx, int *al, void *add_arg)
2547 {
2548     int *server = (int *)add_arg;
2549     unsigned char *data;
2550
2551     if (SSL_is_server(s))
2552         srvaddnewcb++;
2553     else
2554         clntaddnewcb++;
2555
2556     if (*server != SSL_is_server(s)
2557             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
2558         return -1;
2559
2560     *data = 1;
2561     *out = data;
2562     *outlen = sizeof(*data);
2563     return 1;
2564 }
2565
2566 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
2567                         const unsigned char *out, void *add_arg)
2568 {
2569     OPENSSL_free((unsigned char *)out);
2570 }
2571
2572 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
2573                         const unsigned char *in, size_t inlen, X509 *x,
2574                         size_t chainidx, int *al, void *parse_arg)
2575 {
2576     int *server = (int *)parse_arg;
2577
2578     if (SSL_is_server(s))
2579         srvparsenewcb++;
2580     else
2581         clntparsenewcb++;
2582
2583     if (*server != SSL_is_server(s)
2584             || inlen != sizeof(char) || *in != 1)
2585         return -1;
2586
2587     return 1;
2588 }
2589
2590 static int sni_cb(SSL *s, int *al, void *arg)
2591 {
2592     SSL_CTX *ctx = (SSL_CTX *)arg;
2593
2594     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
2595         *al = SSL_AD_INTERNAL_ERROR;
2596         return SSL_TLSEXT_ERR_ALERT_FATAL;
2597     }
2598     snicb++;
2599     return SSL_TLSEXT_ERR_OK;
2600 }
2601
2602 /*
2603  * Custom call back tests.
2604  * Test 0: Old style callbacks in TLSv1.2
2605  * Test 1: New style callbacks in TLSv1.2
2606  * Test 2: New style callbacks in TLSv1.2 with SNI
2607  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
2608  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
2609  */
2610 static int test_custom_exts(int tst)
2611 {
2612     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
2613     SSL *clientssl = NULL, *serverssl = NULL;
2614     int testresult = 0;
2615     static int server = 1;
2616     static int client = 0;
2617     SSL_SESSION *sess = NULL;
2618     unsigned int context;
2619
2620     /* Reset callback counters */
2621     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
2622     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
2623     snicb = 0;
2624
2625     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2626                                        TLS_client_method(), &sctx,
2627                                        &cctx, cert, privkey)))
2628         goto end;
2629
2630     if (tst == 2
2631             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL, &sctx2,
2632                                               NULL, cert, privkey)))
2633         goto end;
2634
2635
2636     if (tst < 3) {
2637         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
2638         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
2639         if (sctx2 != NULL)
2640             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
2641     }
2642
2643     if (tst == 4) {
2644         context = SSL_EXT_CLIENT_HELLO
2645                   | SSL_EXT_TLS1_2_SERVER_HELLO
2646                   | SSL_EXT_TLS1_3_SERVER_HELLO
2647                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
2648                   | SSL_EXT_TLS1_3_CERTIFICATE
2649                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
2650     } else {
2651         context = SSL_EXT_CLIENT_HELLO
2652                   | SSL_EXT_TLS1_2_SERVER_HELLO
2653                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
2654     }
2655
2656     /* Create a client side custom extension */
2657     if (tst == 0) {
2658         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
2659                                                      old_add_cb, old_free_cb,
2660                                                      &client, old_parse_cb,
2661                                                      &client)))
2662             goto end;
2663     } else {
2664         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
2665                                               new_add_cb, new_free_cb,
2666                                               &client, new_parse_cb, &client)))
2667             goto end;
2668     }
2669
2670     /* Should not be able to add duplicates */
2671     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
2672                                                   old_add_cb, old_free_cb,
2673                                                   &client, old_parse_cb,
2674                                                   &client))
2675             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
2676                                                   context, new_add_cb,
2677                                                   new_free_cb, &client,
2678                                                   new_parse_cb, &client)))
2679         goto end;
2680
2681     /* Create a server side custom extension */
2682     if (tst == 0) {
2683         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
2684                                                      old_add_cb, old_free_cb,
2685                                                      &server, old_parse_cb,
2686                                                      &server)))
2687             goto end;
2688     } else {
2689         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
2690                                               new_add_cb, new_free_cb,
2691                                               &server, new_parse_cb, &server)))
2692             goto end;
2693         if (sctx2 != NULL
2694                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
2695                                                      context, new_add_cb,
2696                                                      new_free_cb, &server,
2697                                                      new_parse_cb, &server)))
2698             goto end;
2699     }
2700
2701     /* Should not be able to add duplicates */
2702     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
2703                                                   old_add_cb, old_free_cb,
2704                                                   &server, old_parse_cb,
2705                                                   &server))
2706             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
2707                                                   context, new_add_cb,
2708                                                   new_free_cb, &server,
2709                                                   new_parse_cb, &server)))
2710         goto end;
2711
2712     if (tst == 2) {
2713         /* Set up SNI */
2714         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
2715                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
2716             goto end;
2717     }
2718
2719     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2720                                       &clientssl, NULL, NULL))
2721             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2722                                                 SSL_ERROR_NONE)))
2723         goto end;
2724
2725     if (tst == 0) {
2726         if (clntaddoldcb != 1
2727                 || clntparseoldcb != 1
2728                 || srvaddoldcb != 1
2729                 || srvparseoldcb != 1)
2730             goto end;
2731     } else if (tst == 1 || tst == 2 || tst == 3) {
2732         if (clntaddnewcb != 1
2733                 || clntparsenewcb != 1
2734                 || srvaddnewcb != 1
2735                 || srvparsenewcb != 1
2736                 || (tst != 2 && snicb != 0)
2737                 || (tst == 2 && snicb != 1))
2738             goto end;
2739     } else {
2740         if (clntaddnewcb != 1
2741                 || clntparsenewcb != 4
2742                 || srvaddnewcb != 4
2743                 || srvparsenewcb != 1)
2744             goto end;
2745     }
2746
2747     sess = SSL_get1_session(clientssl);
2748     SSL_shutdown(clientssl);
2749     SSL_shutdown(serverssl);
2750     SSL_free(serverssl);
2751     SSL_free(clientssl);
2752     serverssl = clientssl = NULL;
2753
2754     if (tst == 3) {
2755         /* We don't bother with the resumption aspects for this test */
2756         testresult = 1;
2757         goto end;
2758     }
2759
2760     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2761                                       NULL, NULL))
2762             || !TEST_true(SSL_set_session(clientssl, sess))
2763             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2764                                                SSL_ERROR_NONE)))
2765         goto end;
2766
2767     /*
2768      * For a resumed session we expect to add the ClientHello extension. For the
2769      * old style callbacks we ignore it on the server side because they set
2770      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
2771      * them.
2772      */
2773     if (tst == 0) {
2774         if (clntaddoldcb != 2
2775                 || clntparseoldcb != 1
2776                 || srvaddoldcb != 1
2777                 || srvparseoldcb != 1)
2778             goto end;
2779     } else if (tst == 1 || tst == 2 || tst == 3) {
2780         if (clntaddnewcb != 2
2781                 || clntparsenewcb != 2
2782                 || srvaddnewcb != 2
2783                 || srvparsenewcb != 2)
2784             goto end;
2785     } else {
2786         /* No Certificate message extensions in the resumption handshake */
2787         if (clntaddnewcb != 2
2788                 || clntparsenewcb != 7
2789                 || srvaddnewcb != 7
2790                 || srvparsenewcb != 2)
2791             goto end;
2792     }
2793
2794     testresult = 1;
2795
2796 end:
2797     SSL_SESSION_free(sess);
2798     SSL_free(serverssl);
2799     SSL_free(clientssl);
2800     SSL_CTX_free(sctx2);
2801     SSL_CTX_free(sctx);
2802     SSL_CTX_free(cctx);
2803     return testresult;
2804 }
2805
2806 /*
2807  * Test loading of serverinfo data in various formats. test_sslmessages actually
2808  * tests to make sure the extensions appear in the handshake
2809  */
2810 static int test_serverinfo(int tst)
2811 {
2812     unsigned int version;
2813     unsigned char *sibuf;
2814     size_t sibuflen;
2815     int ret, expected, testresult = 0;
2816     SSL_CTX *ctx;
2817
2818     ctx = SSL_CTX_new(TLS_method());
2819     if (!TEST_ptr(ctx))
2820         goto end;
2821
2822     if ((tst & 0x01) == 0x01)
2823         version = SSL_SERVERINFOV2;
2824     else
2825         version = SSL_SERVERINFOV1;
2826
2827     if ((tst & 0x02) == 0x02) {
2828         sibuf = serverinfov2;
2829         sibuflen = sizeof(serverinfov2);
2830         expected = (version == SSL_SERVERINFOV2);
2831     } else {
2832         sibuf = serverinfov1;
2833         sibuflen = sizeof(serverinfov1);
2834         expected = (version == SSL_SERVERINFOV1);
2835     }
2836
2837     if ((tst & 0x04) == 0x04) {
2838         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
2839     } else {
2840         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
2841
2842         /*
2843          * The version variable is irrelevant in this case - it's what is in the
2844          * buffer that matters
2845          */
2846         if ((tst & 0x02) == 0x02)
2847             expected = 0;
2848         else
2849             expected = 1;
2850     }
2851
2852     if (!TEST_true(ret == expected))
2853         goto end;
2854
2855     testresult = 1;
2856
2857  end:
2858     SSL_CTX_free(ctx);
2859
2860     return testresult;
2861 }
2862
2863 /*
2864  * Test that SSL_export_keying_material() produces expected results. There are
2865  * no test vectors so all we do is test that both sides of the communication
2866  * produce the same results for different protocol versions.
2867  */
2868 static int test_export_key_mat(int tst)
2869 {
2870     int testresult = 0;
2871     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
2872     SSL *clientssl = NULL, *serverssl = NULL;
2873     const char label[] = "test label";
2874     const unsigned char context[] = "context";
2875     const unsigned char *emptycontext = NULL;
2876     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
2877     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
2878     const int protocols[] = {
2879         TLS1_VERSION,
2880         TLS1_1_VERSION,
2881         TLS1_2_VERSION,
2882         TLS1_3_VERSION
2883     };
2884
2885 #ifdef OPENSSL_NO_TLS1
2886     if (tst == 0)
2887         return 1;
2888 #endif
2889 #ifdef OPENSSL_NO_TLS1_1
2890     if (tst == 1)
2891         return 1;
2892 #endif
2893 #ifdef OPENSSL_NO_TLS1_2
2894     if (tst == 2)
2895         return 1;
2896 #endif
2897 #ifdef OPENSSL_NO_TLS1_3
2898     if (tst == 3)
2899         return 1;
2900 #endif
2901     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2902                                        TLS_client_method(), &sctx,
2903                                        &cctx, cert, privkey)))
2904         goto end;
2905
2906     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
2907     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
2908     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
2909
2910     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
2911                                       NULL))
2912             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2913                                                 SSL_ERROR_NONE)))
2914         goto end;
2915
2916     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
2917                                                 sizeof(ckeymat1), label,
2918                                                 sizeof(label) - 1, context,
2919                                                 sizeof(context) - 1, 1), 1)
2920             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
2921                                                        sizeof(ckeymat2), label,
2922                                                        sizeof(label) - 1,
2923                                                        emptycontext,
2924                                                        0, 1), 1)
2925             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
2926                                                        sizeof(ckeymat3), label,
2927                                                        sizeof(label) - 1,
2928                                                        NULL, 0, 0), 1)
2929             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
2930                                                        sizeof(skeymat1), label,
2931                                                        sizeof(label) - 1,
2932                                                        context,
2933                                                        sizeof(context) -1, 1),
2934                             1)
2935             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
2936                                                        sizeof(skeymat2), label,
2937                                                        sizeof(label) - 1,
2938                                                        emptycontext,
2939                                                        0, 1), 1)
2940             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
2941                                                        sizeof(skeymat3), label,
2942                                                        sizeof(label) - 1,
2943                                                        NULL, 0, 0), 1)
2944                /*
2945                 * Check that both sides created the same key material with the
2946                 * same context.
2947                 */
2948             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
2949                             sizeof(skeymat1))
2950                /*
2951                 * Check that both sides created the same key material with an
2952                 * empty context.
2953                 */
2954             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
2955                             sizeof(skeymat2))
2956                /*
2957                 * Check that both sides created the same key material without a
2958                 * context.
2959                 */
2960             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
2961                             sizeof(skeymat3))
2962                /* Different contexts should produce different results */
2963             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
2964                             sizeof(ckeymat2)))
2965         goto end;
2966
2967     /*
2968      * Check that an empty context and no context produce different results in
2969      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
2970      */
2971     if ((tst != 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
2972                                   sizeof(ckeymat3)))
2973             || (tst ==3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
2974                                         sizeof(ckeymat3))))
2975         goto end;
2976
2977     testresult = 1;
2978
2979  end:
2980     SSL_free(serverssl);
2981     SSL_free(clientssl);
2982     SSL_CTX_free(sctx2);
2983     SSL_CTX_free(sctx);
2984     SSL_CTX_free(cctx);
2985
2986     return testresult;
2987 }
2988
2989 static int test_ssl_clear(int idx)
2990 {
2991     SSL_CTX *cctx = NULL, *sctx = NULL;
2992     SSL *clientssl = NULL, *serverssl = NULL;
2993     int testresult = 0;
2994
2995 #ifdef OPENSSL_NO_TLS1_2
2996     if (idx == 1)
2997         return 1;
2998 #endif
2999
3000     /* Create an initial connection */
3001     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
3002                                        TLS_client_method(), &sctx,
3003                                        &cctx, cert, privkey))
3004             || (idx == 1
3005                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
3006                                                             TLS1_2_VERSION)))
3007             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3008                                           &clientssl, NULL, NULL))
3009             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3010                                                 SSL_ERROR_NONE)))
3011         goto end;
3012
3013     SSL_shutdown(clientssl);
3014     SSL_shutdown(serverssl);
3015     SSL_free(serverssl);
3016     serverssl = NULL;
3017
3018     /* Clear clientssl - we're going to reuse the object */
3019     if (!TEST_true(SSL_clear(clientssl)))
3020         goto end;
3021
3022     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3023                                              NULL, NULL))
3024             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3025                                                 SSL_ERROR_NONE))
3026             || !TEST_true(SSL_session_reused(clientssl)))
3027         goto end;
3028
3029     SSL_shutdown(clientssl);
3030     SSL_shutdown(serverssl);
3031
3032     testresult = 1;
3033
3034  end:
3035     SSL_free(serverssl);
3036     SSL_free(clientssl);
3037     SSL_CTX_free(sctx);
3038     SSL_CTX_free(cctx);
3039
3040     return testresult;
3041 }
3042
3043 int setup_tests(void)
3044 {
3045     if (!TEST_ptr(cert = test_get_argument(0))
3046             || !TEST_ptr(privkey = test_get_argument(1)))
3047         return 0;
3048
3049     ADD_TEST(test_large_message_tls);
3050     ADD_TEST(test_large_message_tls_read_ahead);
3051 #ifndef OPENSSL_NO_DTLS
3052     ADD_TEST(test_large_message_dtls);
3053 #endif
3054 #ifndef OPENSSL_NO_OCSP
3055     ADD_TEST(test_tlsext_status_type);
3056 #endif
3057     ADD_TEST(test_session_with_only_int_cache);
3058     ADD_TEST(test_session_with_only_ext_cache);
3059     ADD_TEST(test_session_with_both_cache);
3060     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
3061     ADD_TEST(test_ssl_bio_pop_next_bio);
3062     ADD_TEST(test_ssl_bio_pop_ssl_bio);
3063     ADD_TEST(test_ssl_bio_change_rbio);
3064     ADD_TEST(test_ssl_bio_change_wbio);
3065     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
3066     ADD_TEST(test_keylog);
3067 #ifndef OPENSSL_NO_TLS1_3
3068     ADD_TEST(test_keylog_no_master_key);
3069 #endif
3070 #ifndef OPENSSL_NO_TLS1_2
3071     ADD_TEST(test_early_cb);
3072 #endif
3073 #ifndef OPENSSL_NO_TLS1_3
3074     ADD_ALL_TESTS(test_early_data_read_write, 3);
3075     ADD_ALL_TESTS(test_early_data_skip, 3);
3076     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
3077     ADD_ALL_TESTS(test_early_data_not_sent, 3);
3078     ADD_ALL_TESTS(test_early_data_psk, 7);
3079     ADD_ALL_TESTS(test_early_data_not_expected, 3);
3080 # ifndef OPENSSL_NO_TLS1_2
3081     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
3082 # endif
3083 #endif
3084 #ifndef OPENSSL_NO_TLS1_3
3085     ADD_TEST(test_ciphersuite_change);
3086     ADD_TEST(test_tls13_psk);
3087     ADD_ALL_TESTS(test_custom_exts, 5);
3088 #else
3089     ADD_ALL_TESTS(test_custom_exts, 3);
3090 #endif
3091     ADD_ALL_TESTS(test_serverinfo, 8);
3092     ADD_ALL_TESTS(test_export_key_mat, 4);
3093     ADD_ALL_TESTS(test_ssl_clear, 2);
3094     return 1;
3095 }
3096
3097 void cleanup_tests(void)
3098 {
3099     bio_s_mempacket_test_free();
3100 }