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