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