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