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