Do not lookup zero-length session ID
[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 static int new_called, remove_called, get_called;
761
762 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
763 {
764     new_called++;
765     /*
766      * sess has been up-refed for us, but we don't actually need it so free it
767      * immediately.
768      */
769     SSL_SESSION_free(sess);
770     return 1;
771 }
772
773 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
774 {
775     remove_called++;
776 }
777
778 static SSL_SESSION *get_sess_val = NULL;
779
780 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
781                                    int *copy)
782 {
783     get_called++;
784     *copy = 1;
785     return get_sess_val;
786 }
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
1050 static int test_session_with_only_int_cache(void)
1051 {
1052 #ifndef OPENSSL_NO_TLS1_3
1053     if (!execute_test_session(TLS1_3_VERSION, 1, 0))
1054         return 0;
1055 #endif
1056
1057 #ifndef OPENSSL_NO_TLS1_2
1058     return execute_test_session(TLS1_2_VERSION, 1, 0);
1059 #else
1060     return 1;
1061 #endif
1062 }
1063
1064 static int test_session_with_only_ext_cache(void)
1065 {
1066 #ifndef OPENSSL_NO_TLS1_3
1067     if (!execute_test_session(TLS1_3_VERSION, 0, 1))
1068         return 0;
1069 #endif
1070
1071 #ifndef OPENSSL_NO_TLS1_2
1072     return execute_test_session(TLS1_2_VERSION, 0, 1);
1073 #else
1074     return 1;
1075 #endif
1076 }
1077
1078 static int test_session_with_both_cache(void)
1079 {
1080 #ifndef OPENSSL_NO_TLS1_3
1081     if (!execute_test_session(TLS1_3_VERSION, 1, 1))
1082         return 0;
1083 #endif
1084
1085 #ifndef OPENSSL_NO_TLS1_2
1086     return execute_test_session(TLS1_2_VERSION, 1, 1);
1087 #else
1088     return 1;
1089 #endif
1090 }
1091
1092 #define USE_NULL    0
1093 #define USE_BIO_1   1
1094 #define USE_BIO_2   2
1095
1096 #define TOTAL_SSL_SET_BIO_TESTS (3 * 3 * 3 * 3)
1097
1098 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
1099 {
1100     switch (type) {
1101     case USE_NULL:
1102         *res = NULL;
1103         break;
1104     case USE_BIO_1:
1105         *res = bio1;
1106         break;
1107     case USE_BIO_2:
1108         *res = bio2;
1109         break;
1110     }
1111 }
1112
1113 static int test_ssl_set_bio(int idx)
1114 {
1115     SSL_CTX *ctx;
1116     BIO *bio1 = NULL;
1117     BIO *bio2 = NULL;
1118     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
1119     SSL *ssl = NULL;
1120     int initrbio, initwbio, newrbio, newwbio;
1121     int testresult = 0;
1122
1123     initrbio = idx % 3;
1124     idx /= 3;
1125     initwbio = idx % 3;
1126     idx /= 3;
1127     newrbio = idx % 3;
1128     idx /= 3;
1129     newwbio = idx;
1130     if (!TEST_int_le(newwbio, 2))
1131         return 0;
1132
1133     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
1134                 || !TEST_ptr(ssl = SSL_new(ctx)))
1135         goto end;
1136
1137     if (initrbio == USE_BIO_1
1138             || initwbio == USE_BIO_1
1139             || newrbio == USE_BIO_1
1140             || newwbio == USE_BIO_1) {
1141         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
1142             goto end;
1143     }
1144
1145     if (initrbio == USE_BIO_2
1146             || initwbio == USE_BIO_2
1147             || newrbio == USE_BIO_2
1148             || newwbio == USE_BIO_2) {
1149         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
1150             goto end;
1151     }
1152
1153     setupbio(&irbio, bio1, bio2, initrbio);
1154     setupbio(&iwbio, bio1, bio2, initwbio);
1155
1156     /*
1157      * We want to maintain our own refs to these BIO, so do an up ref for each
1158      * BIO that will have ownership transferred in the SSL_set_bio() call
1159      */
1160     if (irbio != NULL)
1161         BIO_up_ref(irbio);
1162     if (iwbio != NULL && iwbio != irbio)
1163         BIO_up_ref(iwbio);
1164
1165     SSL_set_bio(ssl, irbio, iwbio);
1166
1167     setupbio(&nrbio, bio1, bio2, newrbio);
1168     setupbio(&nwbio, bio1, bio2, newwbio);
1169
1170     /*
1171      * We will (maybe) transfer ownership again so do more up refs.
1172      * SSL_set_bio() has some really complicated ownership rules where BIOs have
1173      * already been set!
1174      */
1175     if (nrbio != NULL
1176             && nrbio != irbio
1177             && (nwbio != iwbio || nrbio != nwbio))
1178         BIO_up_ref(nrbio);
1179     if (nwbio != NULL
1180             && nwbio != nrbio
1181             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
1182         BIO_up_ref(nwbio);
1183
1184     SSL_set_bio(ssl, nrbio, nwbio);
1185
1186     testresult = 1;
1187
1188  end:
1189     SSL_free(ssl);
1190     BIO_free(bio1);
1191     BIO_free(bio2);
1192
1193     /*
1194      * This test is checking that the ref counting for SSL_set_bio is correct.
1195      * If we get here and we did too many frees then we will fail in the above
1196      * functions. If we haven't done enough then this will only be detected in
1197      * a crypto-mdebug build
1198      */
1199     SSL_CTX_free(ctx);
1200     return testresult;
1201 }
1202
1203 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
1204
1205 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
1206 {
1207     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
1208     SSL_CTX *ctx;
1209     SSL *ssl = NULL;
1210     int testresult = 0;
1211
1212     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
1213             || !TEST_ptr(ssl = SSL_new(ctx))
1214             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
1215             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
1216         goto end;
1217
1218     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
1219
1220     /*
1221      * If anything goes wrong here then we could leak memory, so this will
1222      * be caught in a crypto-mdebug build
1223      */
1224     BIO_push(sslbio, membio1);
1225
1226     /* Verify changing the rbio/wbio directly does not cause leaks */
1227     if (change_bio != NO_BIO_CHANGE) {
1228         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem())))
1229             goto end;
1230         if (change_bio == CHANGE_RBIO)
1231             SSL_set0_rbio(ssl, membio2);
1232         else
1233             SSL_set0_wbio(ssl, membio2);
1234     }
1235     ssl = NULL;
1236
1237     if (pop_ssl)
1238         BIO_pop(sslbio);
1239     else
1240         BIO_pop(membio1);
1241
1242     testresult = 1;
1243  end:
1244     BIO_free(membio1);
1245     BIO_free(sslbio);
1246     SSL_free(ssl);
1247     SSL_CTX_free(ctx);
1248
1249     return testresult;
1250 }
1251
1252 static int test_ssl_bio_pop_next_bio(void)
1253 {
1254     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
1255 }
1256
1257 static int test_ssl_bio_pop_ssl_bio(void)
1258 {
1259     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
1260 }
1261
1262 static int test_ssl_bio_change_rbio(void)
1263 {
1264     return execute_test_ssl_bio(0, CHANGE_RBIO);
1265 }
1266
1267 static int test_ssl_bio_change_wbio(void)
1268 {
1269     return execute_test_ssl_bio(0, CHANGE_WBIO);
1270 }
1271
1272 typedef struct {
1273     /* The list of sig algs */
1274     const int *list;
1275     /* The length of the list */
1276     size_t listlen;
1277     /* A sigalgs list in string format */
1278     const char *liststr;
1279     /* Whether setting the list should succeed */
1280     int valid;
1281     /* Whether creating a connection with the list should succeed */
1282     int connsuccess;
1283 } sigalgs_list;
1284
1285 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
1286 #ifndef OPENSSL_NO_EC
1287 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
1288 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
1289 #endif
1290 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
1291 static const int invalidlist2[] = {NID_sha256, NID_undef};
1292 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
1293 static const int invalidlist4[] = {NID_sha256};
1294 static const sigalgs_list testsigalgs[] = {
1295     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
1296 #ifndef OPENSSL_NO_EC
1297     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
1298     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
1299 #endif
1300     {NULL, 0, "RSA+SHA256", 1, 1},
1301 #ifndef OPENSSL_NO_EC
1302     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
1303     {NULL, 0, "ECDSA+SHA512", 1, 0},
1304 #endif
1305     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
1306     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
1307     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
1308     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
1309     {NULL, 0, "RSA", 0, 0},
1310     {NULL, 0, "SHA256", 0, 0},
1311     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
1312     {NULL, 0, "Invalid", 0, 0}
1313 };
1314
1315 static int test_set_sigalgs(int idx)
1316 {
1317     SSL_CTX *cctx = NULL, *sctx = NULL;
1318     SSL *clientssl = NULL, *serverssl = NULL;
1319     int testresult = 0;
1320     const sigalgs_list *curr;
1321     int testctx;
1322
1323     /* Should never happen */
1324     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
1325         return 0;
1326
1327     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
1328     curr = testctx ? &testsigalgs[idx]
1329                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
1330
1331     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1332                                        TLS_client_method(), &sctx,
1333                                        &cctx, cert, privkey)))
1334         return 0;
1335
1336     /*
1337      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
1338      * for TLSv1.2 for now until we add a new API.
1339      */
1340     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1341
1342     if (testctx) {
1343         int ret;
1344
1345         if (curr->list != NULL)
1346             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
1347         else
1348             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
1349
1350         if (!ret) {
1351             if (curr->valid)
1352                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
1353             else
1354                 testresult = 1;
1355             goto end;
1356         }
1357         if (!curr->valid) {
1358             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
1359             goto end;
1360         }
1361     }
1362
1363     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1364                                       &clientssl, NULL, NULL)))
1365         goto end;
1366
1367     if (!testctx) {
1368         int ret;
1369
1370         if (curr->list != NULL)
1371             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
1372         else
1373             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
1374         if (!ret) {
1375             if (curr->valid)
1376                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
1377             else
1378                 testresult = 1;
1379             goto end;
1380         }
1381         if (!curr->valid)
1382             goto end;
1383     }
1384
1385     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
1386                                            SSL_ERROR_NONE),
1387                 curr->connsuccess))
1388         goto end;
1389
1390     testresult = 1;
1391
1392  end:
1393     SSL_free(serverssl);
1394     SSL_free(clientssl);
1395     SSL_CTX_free(sctx);
1396     SSL_CTX_free(cctx);
1397
1398     return testresult;
1399 }
1400
1401 #ifndef OPENSSL_NO_TLS1_3
1402
1403 #define MSG1    "Hello"
1404 #define MSG2    "World."
1405 #define MSG3    "This"
1406 #define MSG4    "is"
1407 #define MSG5    "a"
1408 #define MSG6    "test"
1409 #define MSG7    "message."
1410
1411 /*
1412  * Helper method to setup objects for early data test. Caller frees objects on
1413  * error.
1414  */
1415 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
1416                                 SSL **serverssl, SSL_SESSION **sess, int idx)
1417 {
1418     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1419                                        TLS_client_method(), sctx,
1420                                        cctx, cert, privkey)))
1421         return 0;
1422
1423     /* When idx == 1 we repeat the tests with read_ahead set */
1424     if (idx > 0) {
1425         SSL_CTX_set_read_ahead(*cctx, 1);
1426         SSL_CTX_set_read_ahead(*sctx, 1);
1427     }
1428
1429     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
1430                                       NULL, NULL))
1431             || !TEST_true(create_ssl_connection(*serverssl, *clientssl,
1432                                                 SSL_ERROR_NONE)))
1433         return 0;
1434
1435     *sess = SSL_get1_session(*clientssl);
1436     SSL_shutdown(*clientssl);
1437     SSL_shutdown(*serverssl);
1438     SSL_free(*serverssl);
1439     SSL_free(*clientssl);
1440     *serverssl = *clientssl = NULL;
1441
1442     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
1443                                       clientssl, NULL, NULL))
1444             || !TEST_true(SSL_set_session(*clientssl, *sess)))
1445         return 0;
1446
1447     return 1;
1448 }
1449
1450 static int test_early_data_read_write(int idx)
1451 {
1452     SSL_CTX *cctx = NULL, *sctx = NULL;
1453     SSL *clientssl = NULL, *serverssl = NULL;
1454     int testresult = 0;
1455     SSL_SESSION *sess = NULL;
1456     unsigned char buf[20], data[1024];
1457     size_t readbytes, written, eoedlen, rawread, rawwritten;
1458     BIO *rbio;
1459
1460     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1461                                         &serverssl, &sess, idx)))
1462         goto end;
1463
1464     /* Write and read some early data */
1465     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1466                                         &written))
1467             || !TEST_size_t_eq(written, strlen(MSG1))
1468             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
1469                                                 sizeof(buf), &readbytes),
1470                             SSL_READ_EARLY_DATA_SUCCESS)
1471             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
1472             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1473                             SSL_EARLY_DATA_ACCEPTED))
1474         goto end;
1475
1476     /*
1477      * Server should be able to write data, and client should be able to
1478      * read it.
1479      */
1480     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
1481                                         &written))
1482             || !TEST_size_t_eq(written, strlen(MSG2))
1483             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1484             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1485         goto end;
1486
1487     /* Even after reading normal data, client should be able write early data */
1488     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
1489                                         &written))
1490             || !TEST_size_t_eq(written, strlen(MSG3)))
1491         goto end;
1492
1493     /* Server should still be able read early data after writing data */
1494     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1495                                          &readbytes),
1496                      SSL_READ_EARLY_DATA_SUCCESS)
1497             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
1498         goto end;
1499
1500     /* Write more data from server and read it from client */
1501     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
1502                                         &written))
1503             || !TEST_size_t_eq(written, strlen(MSG4))
1504             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1505             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
1506         goto end;
1507
1508     /*
1509      * If client writes normal data it should mean writing early data is no
1510      * longer possible.
1511      */
1512     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
1513             || !TEST_size_t_eq(written, strlen(MSG5))
1514             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1515                             SSL_EARLY_DATA_ACCEPTED))
1516         goto end;
1517
1518     /*
1519      * At this point the client has written EndOfEarlyData, ClientFinished and
1520      * normal (fully protected) data. We are going to cause a delay between the
1521      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
1522      * in the read BIO, and then just put back the EndOfEarlyData message.
1523      */
1524     rbio = SSL_get_rbio(serverssl);
1525     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
1526             || !TEST_size_t_lt(rawread, sizeof(data))
1527             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
1528         goto end;
1529
1530     /* Record length is in the 4th and 5th bytes of the record header */
1531     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
1532     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
1533             || !TEST_size_t_eq(rawwritten, eoedlen))
1534         goto end;
1535
1536     /* Server should be told that there is no more early data */
1537     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1538                                          &readbytes),
1539                      SSL_READ_EARLY_DATA_FINISH)
1540             || !TEST_size_t_eq(readbytes, 0))
1541         goto end;
1542
1543     /*
1544      * Server has not finished init yet, so should still be able to write early
1545      * data.
1546      */
1547     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
1548                                         &written))
1549             || !TEST_size_t_eq(written, strlen(MSG6)))
1550         goto end;
1551
1552     /* Push the ClientFinished and the normal data back into the server rbio */
1553     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
1554                                 &rawwritten))
1555             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
1556         goto end;
1557
1558     /* Server should be able to read normal data */
1559     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1560             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
1561         goto end;
1562
1563     /* Client and server should not be able to write/read early data now */
1564     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
1565                                          &written)))
1566         goto end;
1567     ERR_clear_error();
1568     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1569                                          &readbytes),
1570                      SSL_READ_EARLY_DATA_ERROR))
1571         goto end;
1572     ERR_clear_error();
1573
1574     /* Client should be able to read the data sent by the server */
1575     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1576             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
1577         goto end;
1578
1579     /*
1580      * Make sure we process the NewSessionTicket. This arrives post-handshake.
1581      * We attempt a read which we do not expect to return any data.
1582      */
1583     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)))
1584         goto end;
1585
1586     /* Server should be able to write normal data */
1587     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
1588             || !TEST_size_t_eq(written, strlen(MSG7))
1589             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1590             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
1591         goto end;
1592
1593     SSL_SESSION_free(sess);
1594     sess = SSL_get1_session(clientssl);
1595
1596     SSL_shutdown(clientssl);
1597     SSL_shutdown(serverssl);
1598     SSL_free(serverssl);
1599     SSL_free(clientssl);
1600     serverssl = clientssl = NULL;
1601     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1602                                       &clientssl, NULL, NULL))
1603             || !TEST_true(SSL_set_session(clientssl, sess)))
1604         goto end;
1605
1606     /* Write and read some early data */
1607     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1608                                         &written))
1609             || !TEST_size_t_eq(written, strlen(MSG1))
1610             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1611                                                 &readbytes),
1612                             SSL_READ_EARLY_DATA_SUCCESS)
1613             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
1614         goto end;
1615
1616     if (!TEST_int_gt(SSL_connect(clientssl), 0)
1617             || !TEST_int_gt(SSL_accept(serverssl), 0))
1618         goto end;
1619
1620     /* Client and server should not be able to write/read early data now */
1621     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
1622                                          &written)))
1623         goto end;
1624     ERR_clear_error();
1625     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1626                                          &readbytes),
1627                      SSL_READ_EARLY_DATA_ERROR))
1628         goto end;
1629     ERR_clear_error();
1630
1631     /* Client and server should be able to write/read normal data */
1632     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
1633             || !TEST_size_t_eq(written, strlen(MSG5))
1634             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1635             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
1636         goto end;
1637
1638     testresult = 1;
1639
1640  end:
1641     SSL_SESSION_free(sess);
1642     SSL_free(serverssl);
1643     SSL_free(clientssl);
1644     SSL_CTX_free(sctx);
1645     SSL_CTX_free(cctx);
1646     return testresult;
1647 }
1648
1649 /*
1650  * Helper function to test that a server attempting to read early data can
1651  * handle a connection from a client where the early data should be skipped.
1652  */
1653 static int early_data_skip_helper(int hrr, int idx)
1654 {
1655     SSL_CTX *cctx = NULL, *sctx = NULL;
1656     SSL *clientssl = NULL, *serverssl = NULL;
1657     int testresult = 0;
1658     SSL_SESSION *sess = NULL;
1659     unsigned char buf[20];
1660     size_t readbytes, written;
1661
1662     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1663                                         &serverssl, &sess, idx)))
1664         goto end;
1665
1666     if (hrr) {
1667         /* Force an HRR to occur */
1668         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
1669             goto end;
1670     } else {
1671         /*
1672          * Deliberately corrupt the creation time. We take 20 seconds off the
1673          * time. It could be any value as long as it is not within tolerance.
1674          * This should mean the ticket is rejected.
1675          */
1676         if (!TEST_true(SSL_SESSION_set_time(sess, time(NULL) - 20)))
1677             goto end;
1678     }
1679
1680     /* Write some early data */
1681     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1682                                         &written))
1683             || !TEST_size_t_eq(written, strlen(MSG1)))
1684         goto end;
1685
1686     /* Server should reject the early data and skip over it */
1687     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1688                                          &readbytes),
1689                      SSL_READ_EARLY_DATA_FINISH)
1690             || !TEST_size_t_eq(readbytes, 0)
1691             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1692                             SSL_EARLY_DATA_REJECTED))
1693         goto end;
1694
1695     if (hrr) {
1696         /*
1697          * Finish off the handshake. We perform the same writes and reads as
1698          * further down but we expect them to fail due to the incomplete
1699          * handshake.
1700          */
1701         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
1702                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
1703                                &readbytes)))
1704             goto end;
1705     }
1706
1707     /* Should be able to send normal data despite rejection of early data */
1708     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
1709             || !TEST_size_t_eq(written, strlen(MSG2))
1710             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1711                             SSL_EARLY_DATA_REJECTED)
1712             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1713             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1714         goto end;
1715
1716     testresult = 1;
1717
1718  end:
1719     SSL_SESSION_free(sess);
1720     SSL_free(serverssl);
1721     SSL_free(clientssl);
1722     SSL_CTX_free(sctx);
1723     SSL_CTX_free(cctx);
1724     return testresult;
1725 }
1726
1727 /*
1728  * Test that a server attempting to read early data can handle a connection
1729  * from a client where the early data is not acceptable.
1730  */
1731 static int test_early_data_skip(int idx)
1732 {
1733     return early_data_skip_helper(0, idx);
1734 }
1735
1736 /*
1737  * Test that a server attempting to read early data can handle a connection
1738  * from a client where an HRR occurs.
1739  */
1740 static int test_early_data_skip_hrr(int idx)
1741 {
1742     return early_data_skip_helper(1, idx);
1743 }
1744
1745 /*
1746  * Test that a server attempting to read early data can handle a connection
1747  * from a client that doesn't send any.
1748  */
1749 static int test_early_data_not_sent(int idx)
1750 {
1751     SSL_CTX *cctx = NULL, *sctx = NULL;
1752     SSL *clientssl = NULL, *serverssl = NULL;
1753     int testresult = 0;
1754     SSL_SESSION *sess = NULL;
1755     unsigned char buf[20];
1756     size_t readbytes, written;
1757
1758     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1759                                         &serverssl, &sess, idx)))
1760         goto end;
1761
1762     /* Write some data - should block due to handshake with server */
1763     SSL_set_connect_state(clientssl);
1764     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
1765         goto end;
1766
1767     /* Server should detect that early data has not been sent */
1768     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1769                                          &readbytes),
1770                      SSL_READ_EARLY_DATA_FINISH)
1771             || !TEST_size_t_eq(readbytes, 0)
1772             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1773                             SSL_EARLY_DATA_NOT_SENT)
1774             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1775                             SSL_EARLY_DATA_NOT_SENT))
1776         goto end;
1777
1778     /* Continue writing the message we started earlier */
1779     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
1780             || !TEST_size_t_eq(written, strlen(MSG1))
1781             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1782             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
1783             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
1784             || !TEST_size_t_eq(written, strlen(MSG2)))
1785         goto end;
1786
1787     /*
1788      * Should block due to the NewSessionTicket arrival unless we're using
1789      * read_ahead
1790      */
1791     if (idx == 0) {
1792         if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)))
1793             goto end;
1794     }
1795
1796     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1797             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1798         goto end;
1799
1800     testresult = 1;
1801
1802  end:
1803     SSL_SESSION_free(sess);
1804     SSL_free(serverssl);
1805     SSL_free(clientssl);
1806     SSL_CTX_free(sctx);
1807     SSL_CTX_free(cctx);
1808     return testresult;
1809 }
1810
1811 /*
1812  * Test that a server that doesn't try to read early data can handle a
1813  * client sending some.
1814  */
1815 static int test_early_data_not_expected(int idx)
1816 {
1817     SSL_CTX *cctx = NULL, *sctx = NULL;
1818     SSL *clientssl = NULL, *serverssl = NULL;
1819     int testresult = 0;
1820     SSL_SESSION *sess = NULL;
1821     unsigned char buf[20];
1822     size_t readbytes, written;
1823
1824
1825     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1826                                         &serverssl, &sess, idx)))
1827         goto end;
1828
1829     /* Write some early data */
1830     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1831                                         &written)))
1832         goto end;
1833
1834     /*
1835      * Server should skip over early data and then block waiting for client to
1836      * continue handshake
1837      */
1838     if (!TEST_int_le(SSL_accept(serverssl), 0)
1839      || !TEST_int_gt(SSL_connect(clientssl), 0)
1840      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1841                      SSL_EARLY_DATA_REJECTED)
1842      || !TEST_int_gt(SSL_accept(serverssl), 0)
1843      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1844                      SSL_EARLY_DATA_REJECTED))
1845         goto end;
1846
1847     /* Send some normal data from client to server */
1848     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
1849             || !TEST_size_t_eq(written, strlen(MSG2)))
1850         goto end;
1851
1852     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1853             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1854         goto end;
1855
1856     testresult = 1;
1857
1858  end:
1859     SSL_SESSION_free(sess);
1860     SSL_free(serverssl);
1861     SSL_free(clientssl);
1862     SSL_CTX_free(sctx);
1863     SSL_CTX_free(cctx);
1864     return testresult;
1865 }
1866
1867
1868 # ifndef OPENSSL_NO_TLS1_2
1869 /*
1870  * Test that a server attempting to read early data can handle a connection
1871  * from a TLSv1.2 client.
1872  */
1873 static int test_early_data_tls1_2(int idx)
1874 {
1875     SSL_CTX *cctx = NULL, *sctx = NULL;
1876     SSL *clientssl = NULL, *serverssl = NULL;
1877     int testresult = 0;
1878     unsigned char buf[20];
1879     size_t readbytes, written;
1880
1881     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1882                                        TLS_client_method(), &sctx,
1883                                        &cctx, cert, privkey)))
1884         goto end;
1885
1886     /* When idx == 1 we repeat the tests with read_ahead set */
1887     if (idx > 0) {
1888         SSL_CTX_set_read_ahead(cctx, 1);
1889         SSL_CTX_set_read_ahead(sctx, 1);
1890     }
1891
1892     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1893                                       &clientssl, NULL, NULL)))
1894         goto end;
1895
1896     /* Write some data - should block due to handshake with server */
1897     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
1898     SSL_set_connect_state(clientssl);
1899     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
1900         goto end;
1901
1902     /*
1903      * Server should do TLSv1.2 handshake. First it will block waiting for more
1904      * messages from client after ServerDone. Then SSL_read_early_data should
1905      * finish and detect that early data has not been sent
1906      */
1907     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1908                                          &readbytes),
1909                      SSL_READ_EARLY_DATA_ERROR))
1910         goto end;
1911
1912     /*
1913      * Continue writing the message we started earlier. Will still block waiting
1914      * for the CCS/Finished from server
1915      */
1916     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
1917             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1918                                                 &readbytes),
1919                             SSL_READ_EARLY_DATA_FINISH)
1920             || !TEST_size_t_eq(readbytes, 0)
1921             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1922                             SSL_EARLY_DATA_NOT_SENT))
1923         goto end;
1924
1925     /* Continue writing the message we started earlier */
1926     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
1927             || !TEST_size_t_eq(written, strlen(MSG1))
1928             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1929                             SSL_EARLY_DATA_NOT_SENT)
1930             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1931             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
1932             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
1933             || !TEST_size_t_eq(written, strlen(MSG2))
1934             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
1935             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1936         goto end;
1937
1938     testresult = 1;
1939
1940  end:
1941     SSL_free(serverssl);
1942     SSL_free(clientssl);
1943     SSL_CTX_free(sctx);
1944     SSL_CTX_free(cctx);
1945
1946     return testresult;
1947 }
1948 # endif /* OPENSSL_NO_TLS1_2 */
1949
1950 static int test_ciphersuite_change(void)
1951 {
1952     SSL_CTX *cctx = NULL, *sctx = NULL;
1953     SSL *clientssl = NULL, *serverssl = NULL;
1954     SSL_SESSION *clntsess = NULL;
1955     int testresult = 0;
1956     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
1957
1958     /* Create a session based on SHA-256 */
1959     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1960                                        TLS_client_method(), &sctx,
1961                                        &cctx, cert, privkey))
1962             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
1963                                                   "TLS13-AES-128-GCM-SHA256"))
1964             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1965                                           &clientssl, NULL, NULL))
1966             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1967                                                 SSL_ERROR_NONE)))
1968         goto end;
1969
1970     clntsess = SSL_get1_session(clientssl);
1971     /* Save for later */
1972     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
1973     SSL_shutdown(clientssl);
1974     SSL_shutdown(serverssl);
1975     SSL_free(serverssl);
1976     SSL_free(clientssl);
1977     serverssl = clientssl = NULL;
1978
1979     /* Check we can resume a session with a different SHA-256 ciphersuite */
1980     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
1981                                            "TLS13-CHACHA20-POLY1305-SHA256"))
1982             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1983                                              NULL, NULL))
1984             || !TEST_true(SSL_set_session(clientssl, clntsess))
1985             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1986                                                 SSL_ERROR_NONE))
1987             || !TEST_true(SSL_session_reused(clientssl)))
1988         goto end;
1989
1990     SSL_SESSION_free(clntsess);
1991     clntsess = SSL_get1_session(clientssl);
1992     SSL_shutdown(clientssl);
1993     SSL_shutdown(serverssl);
1994     SSL_free(serverssl);
1995     SSL_free(clientssl);
1996     serverssl = clientssl = NULL;
1997
1998     /*
1999      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
2000      * succeeds but does not resume.
2001      */
2002     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "TLS13-AES-256-GCM-SHA384"))
2003             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2004                                              NULL, NULL))
2005             || !TEST_true(SSL_set_session(clientssl, clntsess))
2006             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2007                                                 SSL_ERROR_SSL))
2008             || !TEST_false(SSL_session_reused(clientssl)))
2009         goto end;
2010
2011     SSL_SESSION_free(clntsess);
2012     clntsess = NULL;
2013     SSL_shutdown(clientssl);
2014     SSL_shutdown(serverssl);
2015     SSL_free(serverssl);
2016     SSL_free(clientssl);
2017     serverssl = clientssl = NULL;
2018
2019     /* Create a session based on SHA384 */
2020     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "TLS13-AES-256-GCM-SHA384"))
2021             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2022                                           &clientssl, NULL, NULL))
2023             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2024                                                 SSL_ERROR_NONE)))
2025         goto end;
2026
2027     clntsess = SSL_get1_session(clientssl);
2028     SSL_shutdown(clientssl);
2029     SSL_shutdown(serverssl);
2030     SSL_free(serverssl);
2031     SSL_free(clientssl);
2032     serverssl = clientssl = NULL;
2033
2034     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
2035                    "TLS13-AES-128-GCM-SHA256:TLS13-AES-256-GCM-SHA384"))
2036             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
2037                                                   "TLS13-AES-256-GCM-SHA384"))
2038             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2039                                              NULL, NULL))
2040             || !TEST_true(SSL_set_session(clientssl, clntsess))
2041                /*
2042                 * We use SSL_ERROR_WANT_READ below so that we can pause the
2043                 * connection after the initial ClientHello has been sent to
2044                 * enable us to make some session changes.
2045                 */
2046             || !TEST_false(create_ssl_connection(serverssl, clientssl,
2047                                                 SSL_ERROR_WANT_READ)))
2048         goto end;
2049
2050     /* Trick the client into thinking this session is for a different digest */
2051     clntsess->cipher = aes_128_gcm_sha256;
2052     clntsess->cipher_id = clntsess->cipher->id;
2053
2054     /*
2055      * Continue the previously started connection. Server has selected a SHA-384
2056      * ciphersuite, but client thinks the session is for SHA-256, so it should
2057      * bail out.
2058      */
2059     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
2060                                                 SSL_ERROR_SSL))
2061             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
2062                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
2063         goto end;
2064
2065     testresult = 1;
2066
2067  end:
2068     SSL_SESSION_free(clntsess);
2069     SSL_free(serverssl);
2070     SSL_free(clientssl);
2071     SSL_CTX_free(sctx);
2072     SSL_CTX_free(cctx);
2073
2074     return testresult;
2075 }
2076
2077
2078 static SSL_SESSION *psk = NULL;
2079 static const char *pskid = "Identity";
2080 static const char *srvid;
2081
2082 static int use_session_cb_cnt = 0;
2083 static int find_session_cb_cnt = 0;
2084
2085 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
2086                           size_t *idlen, SSL_SESSION **sess)
2087 {
2088     switch (++use_session_cb_cnt) {
2089     case 1:
2090         /* The first call should always have a NULL md */
2091         if (md != NULL)
2092             return 0;
2093         break;
2094
2095     case 2:
2096         /* The second call should always have an md */
2097         if (md == NULL)
2098             return 0;
2099         break;
2100
2101     default:
2102         /* We should only be called a maximum of twice */
2103         return 0;
2104     }
2105
2106     if (psk != NULL)
2107         SSL_SESSION_up_ref(psk);
2108
2109     *sess = psk;
2110     *id = (const unsigned char *)pskid;
2111     *idlen = strlen(pskid);
2112
2113     return 1;
2114 }
2115
2116 static int find_session_cb(SSL *ssl, const unsigned char *identity,
2117                            size_t identity_len, SSL_SESSION **sess)
2118 {
2119     find_session_cb_cnt++;
2120
2121     /* We should only ever be called a maximum of twice per connection */
2122     if (find_session_cb_cnt > 2)
2123         return 0;
2124
2125     if (psk == NULL)
2126         return 0;
2127
2128     /* Identity should match that set by the client */
2129     if (strlen(srvid) != identity_len
2130             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
2131         /* No PSK found, continue but without a PSK */
2132         *sess = NULL;
2133         return 1;
2134     }
2135
2136     SSL_SESSION_up_ref(psk);
2137     *sess = psk;
2138
2139     return 1;
2140 }
2141
2142 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
2143
2144 static int test_tls13_psk(void)
2145 {
2146     SSL_CTX *sctx = NULL, *cctx = NULL;
2147     SSL *serverssl = NULL, *clientssl = NULL;
2148     const SSL_CIPHER *cipher = NULL;
2149     const unsigned char key[] = {
2150         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
2151         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
2152         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
2153         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
2154     };
2155     int testresult = 0;
2156
2157     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2158                                        TLS_client_method(), &sctx,
2159                                        &cctx, cert, privkey)))
2160         goto end;
2161
2162     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2163     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2164     srvid = pskid;
2165
2166     /* Check we can create a connection if callback decides not to send a PSK */
2167     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2168                                              NULL, NULL))
2169             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2170                                                 SSL_ERROR_NONE))
2171             || !TEST_false(SSL_session_reused(clientssl))
2172             || !TEST_false(SSL_session_reused(serverssl))
2173             || !TEST_true(use_session_cb_cnt == 1)
2174             || !TEST_true(find_session_cb_cnt == 0))
2175         goto end;
2176
2177     shutdown_ssl_connection(serverssl, clientssl);
2178     serverssl = clientssl = NULL;
2179     use_session_cb_cnt = 0;
2180
2181     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2182                                              NULL, NULL)))
2183         goto end;
2184
2185     /* Create the PSK */
2186     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_256_GCM_SHA384_BYTES);
2187     psk = SSL_SESSION_new();
2188     if (!TEST_ptr(psk)
2189             || !TEST_ptr(cipher)
2190             || !TEST_true(SSL_SESSION_set1_master_key(psk, key, sizeof(key)))
2191             || !TEST_true(SSL_SESSION_set_cipher(psk, cipher))
2192             || !TEST_true(SSL_SESSION_set_protocol_version(psk,
2193                                                            TLS1_3_VERSION)))
2194         goto end;
2195
2196     /* Check we can create a connection and the PSK is used */
2197     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2198             || !TEST_true(SSL_session_reused(clientssl))
2199             || !TEST_true(SSL_session_reused(serverssl))
2200             || !TEST_true(use_session_cb_cnt == 1)
2201             || !TEST_true(find_session_cb_cnt == 1))
2202         goto end;
2203
2204     shutdown_ssl_connection(serverssl, clientssl);
2205     serverssl = clientssl = NULL;
2206     use_session_cb_cnt = find_session_cb_cnt = 0;
2207
2208     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2209                                              NULL, NULL)))
2210         goto end;
2211
2212     /* Force an HRR */
2213     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2214         goto end;
2215
2216     /*
2217      * Check we can create a connection, the PSK is used and the callbacks are
2218      * called twice.
2219      */
2220     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2221             || !TEST_true(SSL_session_reused(clientssl))
2222             || !TEST_true(SSL_session_reused(serverssl))
2223             || !TEST_true(use_session_cb_cnt == 2)
2224             || !TEST_true(find_session_cb_cnt == 2))
2225         goto end;
2226
2227     shutdown_ssl_connection(serverssl, clientssl);
2228     serverssl = clientssl = NULL;
2229     use_session_cb_cnt = find_session_cb_cnt = 0;
2230
2231     /*
2232      * Check that if the server rejects the PSK we can still connect, but with
2233      * a full handshake
2234      */
2235     srvid = "Dummy Identity";
2236     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2237                                              NULL, NULL))
2238             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2239                                                 SSL_ERROR_NONE))
2240             || !TEST_false(SSL_session_reused(clientssl))
2241             || !TEST_false(SSL_session_reused(serverssl))
2242             || !TEST_true(use_session_cb_cnt == 1)
2243             || !TEST_true(find_session_cb_cnt == 1))
2244         goto end;
2245
2246     shutdown_ssl_connection(serverssl, clientssl);
2247     serverssl = clientssl = NULL;
2248     testresult = 1;
2249
2250  end:
2251     SSL_SESSION_free(psk);
2252     SSL_free(serverssl);
2253     SSL_free(clientssl);
2254     SSL_CTX_free(sctx);
2255     SSL_CTX_free(cctx);
2256     return testresult;
2257 }
2258
2259 #endif /* OPENSSL_NO_TLS1_3 */
2260
2261 static int clntaddoldcb = 0;
2262 static int clntparseoldcb = 0;
2263 static int srvaddoldcb = 0;
2264 static int srvparseoldcb = 0;
2265 static int clntaddnewcb = 0;
2266 static int clntparsenewcb = 0;
2267 static int srvaddnewcb = 0;
2268 static int srvparsenewcb = 0;
2269 static int snicb = 0;
2270
2271 #define TEST_EXT_TYPE1  0xff00
2272
2273 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
2274                       size_t *outlen, int *al, void *add_arg)
2275 {
2276     int *server = (int *)add_arg;
2277     unsigned char *data;
2278
2279     if (SSL_is_server(s))
2280         srvaddoldcb++;
2281     else
2282         clntaddoldcb++;
2283
2284     if (*server != SSL_is_server(s)
2285             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
2286         return -1;
2287
2288     *data = 1;
2289     *out = data;
2290     *outlen = sizeof(char);
2291     return 1;
2292 }
2293
2294 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
2295                         void *add_arg)
2296 {
2297     OPENSSL_free((unsigned char *)out);
2298 }
2299
2300 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
2301                         size_t inlen, int *al, void *parse_arg)
2302 {
2303     int *server = (int *)parse_arg;
2304
2305     if (SSL_is_server(s))
2306         srvparseoldcb++;
2307     else
2308         clntparseoldcb++;
2309
2310     if (*server != SSL_is_server(s)
2311             || inlen != sizeof(char)
2312             || *in != 1)
2313         return -1;
2314
2315     return 1;
2316 }
2317
2318 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
2319                       const unsigned char **out, size_t *outlen, X509 *x,
2320                       size_t chainidx, int *al, void *add_arg)
2321 {
2322     int *server = (int *)add_arg;
2323     unsigned char *data;
2324
2325     if (SSL_is_server(s))
2326         srvaddnewcb++;
2327     else
2328         clntaddnewcb++;
2329
2330     if (*server != SSL_is_server(s)
2331             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
2332         return -1;
2333
2334     *data = 1;
2335     *out = data;
2336     *outlen = sizeof(*data);
2337     return 1;
2338 }
2339
2340 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
2341                         const unsigned char *out, void *add_arg)
2342 {
2343     OPENSSL_free((unsigned char *)out);
2344 }
2345
2346 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
2347                         const unsigned char *in, size_t inlen, X509 *x,
2348                         size_t chainidx, int *al, void *parse_arg)
2349 {
2350     int *server = (int *)parse_arg;
2351
2352     if (SSL_is_server(s))
2353         srvparsenewcb++;
2354     else
2355         clntparsenewcb++;
2356
2357     if (*server != SSL_is_server(s)
2358             || inlen != sizeof(char) || *in != 1)
2359         return -1;
2360
2361     return 1;
2362 }
2363
2364 static int sni_cb(SSL *s, int *al, void *arg)
2365 {
2366     SSL_CTX *ctx = (SSL_CTX *)arg;
2367
2368     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
2369         *al = SSL_AD_INTERNAL_ERROR;
2370         return SSL_TLSEXT_ERR_ALERT_FATAL;
2371     }
2372     snicb++;
2373     return SSL_TLSEXT_ERR_OK;
2374 }
2375
2376 /*
2377  * Custom call back tests.
2378  * Test 0: Old style callbacks in TLSv1.2
2379  * Test 1: New style callbacks in TLSv1.2
2380  * Test 2: New style callbacks in TLSv1.2 with SNI
2381  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
2382  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
2383  */
2384 static int test_custom_exts(int tst)
2385 {
2386     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
2387     SSL *clientssl = NULL, *serverssl = NULL;
2388     int testresult = 0;
2389     static int server = 1;
2390     static int client = 0;
2391     SSL_SESSION *sess = NULL;
2392     unsigned int context;
2393
2394     /* Reset callback counters */
2395     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
2396     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
2397     snicb = 0;
2398
2399     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2400                                        TLS_client_method(), &sctx,
2401                                        &cctx, cert, privkey)))
2402         goto end;
2403
2404     if (tst == 2
2405             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL, &sctx2,
2406                                               NULL, cert, privkey)))
2407         goto end;
2408
2409
2410     if (tst < 3) {
2411         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
2412         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
2413         if (sctx2 != NULL)
2414             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
2415     }
2416
2417     if (tst == 4) {
2418         context = SSL_EXT_CLIENT_HELLO
2419                   | SSL_EXT_TLS1_2_SERVER_HELLO
2420                   | SSL_EXT_TLS1_3_SERVER_HELLO
2421                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
2422                   | SSL_EXT_TLS1_3_CERTIFICATE
2423                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
2424     } else {
2425         context = SSL_EXT_CLIENT_HELLO
2426                   | SSL_EXT_TLS1_2_SERVER_HELLO
2427                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
2428     }
2429
2430     /* Create a client side custom extension */
2431     if (tst == 0) {
2432         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
2433                                                      old_add_cb, old_free_cb,
2434                                                      &client, old_parse_cb,
2435                                                      &client)))
2436             goto end;
2437     } else {
2438         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
2439                                               new_add_cb, new_free_cb,
2440                                               &client, new_parse_cb, &client)))
2441             goto end;
2442     }
2443
2444     /* Should not be able to add duplicates */
2445     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
2446                                                   old_add_cb, old_free_cb,
2447                                                   &client, old_parse_cb,
2448                                                   &client))
2449             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
2450                                                   context, new_add_cb,
2451                                                   new_free_cb, &client,
2452                                                   new_parse_cb, &client)))
2453         goto end;
2454
2455     /* Create a server side custom extension */
2456     if (tst == 0) {
2457         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
2458                                                      old_add_cb, old_free_cb,
2459                                                      &server, old_parse_cb,
2460                                                      &server)))
2461             goto end;
2462     } else {
2463         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
2464                                               new_add_cb, new_free_cb,
2465                                               &server, new_parse_cb, &server)))
2466             goto end;
2467         if (sctx2 != NULL
2468                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
2469                                                      context, new_add_cb,
2470                                                      new_free_cb, &server,
2471                                                      new_parse_cb, &server)))
2472             goto end;
2473     }
2474
2475     /* Should not be able to add duplicates */
2476     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
2477                                                   old_add_cb, old_free_cb,
2478                                                   &server, old_parse_cb,
2479                                                   &server))
2480             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
2481                                                   context, new_add_cb,
2482                                                   new_free_cb, &server,
2483                                                   new_parse_cb, &server)))
2484         goto end;
2485
2486     if (tst == 2) {
2487         /* Set up SNI */
2488         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
2489                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
2490             goto end;
2491     }
2492
2493     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2494                                       &clientssl, NULL, NULL))
2495             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2496                                                 SSL_ERROR_NONE)))
2497         goto end;
2498
2499     if (tst == 0) {
2500         if (clntaddoldcb != 1
2501                 || clntparseoldcb != 1
2502                 || srvaddoldcb != 1
2503                 || srvparseoldcb != 1)
2504             goto end;
2505     } else if (tst == 1 || tst == 2 || tst == 3) {
2506         if (clntaddnewcb != 1
2507                 || clntparsenewcb != 1
2508                 || srvaddnewcb != 1
2509                 || srvparsenewcb != 1
2510                 || (tst != 2 && snicb != 0)
2511                 || (tst == 2 && snicb != 1))
2512             goto end;
2513     } else {
2514         if (clntaddnewcb != 1
2515                 || clntparsenewcb != 4
2516                 || srvaddnewcb != 4
2517                 || srvparsenewcb != 1)
2518             goto end;
2519     }
2520
2521     sess = SSL_get1_session(clientssl);
2522     SSL_shutdown(clientssl);
2523     SSL_shutdown(serverssl);
2524     SSL_free(serverssl);
2525     SSL_free(clientssl);
2526     serverssl = clientssl = NULL;
2527
2528     if (tst == 3) {
2529         /* We don't bother with the resumption aspects for this test */
2530         testresult = 1;
2531         goto end;
2532     }
2533
2534     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2535                                       NULL, NULL))
2536             || !TEST_true(SSL_set_session(clientssl, sess))
2537             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2538                                                SSL_ERROR_NONE)))
2539         goto end;
2540
2541     /*
2542      * For a resumed session we expect to add the ClientHello extension. For the
2543      * old style callbacks we ignore it on the server side because they set
2544      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
2545      * them.
2546      */
2547     if (tst == 0) {
2548         if (clntaddoldcb != 2
2549                 || clntparseoldcb != 1
2550                 || srvaddoldcb != 1
2551                 || srvparseoldcb != 1)
2552             goto end;
2553     } else if (tst == 1 || tst == 2 || tst == 3) {
2554         if (clntaddnewcb != 2
2555                 || clntparsenewcb != 2
2556                 || srvaddnewcb != 2
2557                 || srvparsenewcb != 2)
2558             goto end;
2559     } else {
2560         /* No Certificate message extensions in the resumption handshake */
2561         if (clntaddnewcb != 2
2562                 || clntparsenewcb != 7
2563                 || srvaddnewcb != 7
2564                 || srvparsenewcb != 2)
2565             goto end;
2566     }
2567
2568     testresult = 1;
2569
2570 end:
2571     SSL_SESSION_free(sess);
2572     SSL_free(serverssl);
2573     SSL_free(clientssl);
2574     SSL_CTX_free(sctx2);
2575     SSL_CTX_free(sctx);
2576     SSL_CTX_free(cctx);
2577     return testresult;
2578 }
2579
2580 /*
2581  * Test loading of serverinfo data in various formats. test_sslmessages actually
2582  * tests to make sure the extensions appear in the handshake
2583  */
2584 static int test_serverinfo(int tst)
2585 {
2586     unsigned int version;
2587     unsigned char *sibuf;
2588     size_t sibuflen;
2589     int ret, expected, testresult = 0;
2590     SSL_CTX *ctx;
2591
2592     ctx = SSL_CTX_new(TLS_method());
2593     if (!TEST_ptr(ctx))
2594         goto end;
2595
2596     if ((tst & 0x01) == 0x01)
2597         version = SSL_SERVERINFOV2;
2598     else
2599         version = SSL_SERVERINFOV1;
2600
2601     if ((tst & 0x02) == 0x02) {
2602         sibuf = serverinfov2;
2603         sibuflen = sizeof(serverinfov2);
2604         expected = (version == SSL_SERVERINFOV2);
2605     } else {
2606         sibuf = serverinfov1;
2607         sibuflen = sizeof(serverinfov1);
2608         expected = (version == SSL_SERVERINFOV1);
2609     }
2610
2611     if ((tst & 0x04) == 0x04) {
2612         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
2613     } else {
2614         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
2615
2616         /*
2617          * The version variable is irrelevant in this case - it's what is in the
2618          * buffer that matters
2619          */
2620         if ((tst & 0x02) == 0x02)
2621             expected = 0;
2622         else
2623             expected = 1;
2624     }
2625
2626     if (!TEST_true(ret == expected))
2627         goto end;
2628
2629     testresult = 1;
2630
2631  end:
2632     SSL_CTX_free(ctx);
2633
2634     return testresult;
2635 }
2636
2637 /*
2638  * Test that SSL_export_keying_material() produces expected results. There are
2639  * no test vectors so all we do is test that both sides of the communication
2640  * produce the same results for different protocol versions.
2641  */
2642 static int test_export_key_mat(int tst)
2643 {
2644     int testresult = 0;
2645     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
2646     SSL *clientssl = NULL, *serverssl = NULL;
2647     const char label[] = "test label";
2648     const unsigned char context[] = "context";
2649     const unsigned char *emptycontext = NULL;
2650     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
2651     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
2652     const int protocols[] = {
2653         TLS1_VERSION,
2654         TLS1_1_VERSION,
2655         TLS1_2_VERSION,
2656         TLS1_3_VERSION
2657     };
2658
2659 #ifdef OPENSSL_NO_TLS1
2660     if (tst == 0)
2661         return 1;
2662 #endif
2663 #ifdef OPENSSL_NO_TLS1_1
2664     if (tst == 1)
2665         return 1;
2666 #endif
2667 #ifdef OPENSSL_NO_TLS1_2
2668     if (tst == 2)
2669         return 1;
2670 #endif
2671 #ifdef OPENSSL_NO_TLS1_3
2672     if (tst == 3)
2673         return 1;
2674 #endif
2675     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2676                                        TLS_client_method(), &sctx,
2677                                        &cctx, cert, privkey)))
2678         goto end;
2679
2680     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
2681     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
2682     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
2683
2684     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
2685                                       NULL))
2686             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2687                                                 SSL_ERROR_NONE)))
2688         goto end;
2689
2690     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
2691                                                 sizeof(ckeymat1), label,
2692                                                 sizeof(label) - 1, context,
2693                                                 sizeof(context) - 1, 1), 1)
2694             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
2695                                                        sizeof(ckeymat2), label,
2696                                                        sizeof(label) - 1,
2697                                                        emptycontext,
2698                                                        0, 1), 1)
2699             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
2700                                                        sizeof(ckeymat3), label,
2701                                                        sizeof(label) - 1,
2702                                                        NULL, 0, 0), 1)
2703             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
2704                                                        sizeof(skeymat1), label,
2705                                                        sizeof(label) - 1,
2706                                                        context,
2707                                                        sizeof(context) -1, 1),
2708                             1)
2709             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
2710                                                        sizeof(skeymat2), label,
2711                                                        sizeof(label) - 1,
2712                                                        emptycontext,
2713                                                        0, 1), 1)
2714             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
2715                                                        sizeof(skeymat3), label,
2716                                                        sizeof(label) - 1,
2717                                                        NULL, 0, 0), 1)
2718                /*
2719                 * Check that both sides created the same key material with the
2720                 * same context.
2721                 */
2722             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
2723                             sizeof(skeymat1))
2724                /*
2725                 * Check that both sides created the same key material with an
2726                 * empty context.
2727                 */
2728             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
2729                             sizeof(skeymat2))
2730                /*
2731                 * Check that both sides created the same key material without a
2732                 * context.
2733                 */
2734             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
2735                             sizeof(skeymat3))
2736                /* Different contexts should produce different results */
2737             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
2738                             sizeof(ckeymat2)))
2739         goto end;
2740
2741     /*
2742      * Check that an empty context and no context produce different results in
2743      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
2744      */
2745     if ((tst != 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
2746                                   sizeof(ckeymat3)))
2747             || (tst ==3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
2748                                         sizeof(ckeymat3))))
2749         goto end;
2750
2751     testresult = 1;
2752
2753  end:
2754     SSL_free(serverssl);
2755     SSL_free(clientssl);
2756     SSL_CTX_free(sctx2);
2757     SSL_CTX_free(sctx);
2758     SSL_CTX_free(cctx);
2759
2760     return testresult;
2761 }
2762
2763 static int test_ssl_clear(int idx)
2764 {
2765     SSL_CTX *cctx = NULL, *sctx = NULL;
2766     SSL *clientssl = NULL, *serverssl = NULL;
2767     int testresult = 0;
2768
2769 #ifdef OPENSSL_NO_TLS1_2
2770     if (idx == 1)
2771         return 1;
2772 #endif
2773
2774     /* Create an initial connection */
2775     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2776                                        TLS_client_method(), &sctx,
2777                                        &cctx, cert, privkey))
2778             || (idx == 1
2779                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
2780                                                             TLS1_2_VERSION)))
2781             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2782                                           &clientssl, NULL, NULL))
2783             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2784                                                 SSL_ERROR_NONE)))
2785         goto end;
2786
2787     SSL_shutdown(clientssl);
2788     SSL_shutdown(serverssl);
2789     SSL_free(serverssl);
2790     serverssl = NULL;
2791
2792     /* Clear clientssl - we're going to reuse the object */
2793     if (!TEST_true(SSL_clear(clientssl)))
2794         goto end;
2795
2796     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2797                                              NULL, NULL))
2798             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2799                                                 SSL_ERROR_NONE))
2800             || !TEST_true(SSL_session_reused(clientssl)))
2801         goto end;
2802
2803     SSL_shutdown(clientssl);
2804     SSL_shutdown(serverssl);
2805
2806     testresult = 1;
2807
2808  end:
2809     SSL_free(serverssl);
2810     SSL_free(clientssl);
2811     SSL_CTX_free(sctx);
2812     SSL_CTX_free(cctx);
2813
2814     return testresult;
2815 }
2816
2817 int setup_tests(void)
2818 {
2819     if (!TEST_ptr(cert = test_get_argument(0))
2820             || !TEST_ptr(privkey = test_get_argument(1)))
2821         return 0;
2822
2823     ADD_TEST(test_large_message_tls);
2824     ADD_TEST(test_large_message_tls_read_ahead);
2825 #ifndef OPENSSL_NO_DTLS
2826     ADD_TEST(test_large_message_dtls);
2827 #endif
2828 #ifndef OPENSSL_NO_OCSP
2829     ADD_TEST(test_tlsext_status_type);
2830 #endif
2831     ADD_TEST(test_session_with_only_int_cache);
2832     ADD_TEST(test_session_with_only_ext_cache);
2833     ADD_TEST(test_session_with_both_cache);
2834     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
2835     ADD_TEST(test_ssl_bio_pop_next_bio);
2836     ADD_TEST(test_ssl_bio_pop_ssl_bio);
2837     ADD_TEST(test_ssl_bio_change_rbio);
2838     ADD_TEST(test_ssl_bio_change_wbio);
2839     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
2840     ADD_TEST(test_keylog);
2841 #ifndef OPENSSL_NO_TLS1_3
2842     ADD_TEST(test_keylog_no_master_key);
2843 #endif
2844 #ifndef OPENSSL_NO_TLS1_2
2845     ADD_TEST(test_early_cb);
2846 #endif
2847 #ifndef OPENSSL_NO_TLS1_3
2848     ADD_ALL_TESTS(test_early_data_read_write, 2);
2849     ADD_ALL_TESTS(test_early_data_skip, 2);
2850     ADD_ALL_TESTS(test_early_data_skip_hrr, 2);
2851     ADD_ALL_TESTS(test_early_data_not_sent, 2);
2852     ADD_ALL_TESTS(test_early_data_not_expected, 2);
2853 # ifndef OPENSSL_NO_TLS1_2
2854     ADD_ALL_TESTS(test_early_data_tls1_2, 2);
2855 # endif
2856 #endif
2857 #ifndef OPENSSL_NO_TLS1_3
2858     ADD_TEST(test_ciphersuite_change);
2859     ADD_TEST(test_tls13_psk);
2860     ADD_ALL_TESTS(test_custom_exts, 5);
2861 #else
2862     ADD_ALL_TESTS(test_custom_exts, 3);
2863 #endif
2864     ADD_ALL_TESTS(test_serverinfo, 8);
2865     ADD_ALL_TESTS(test_export_key_mat, 4);
2866     ADD_ALL_TESTS(test_ssl_clear, 2);
2867     return 1;
2868 }
2869
2870 void cleanup_tests(void)
2871 {
2872     bio_s_mempacket_test_free();
2873 }