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