Fix minor typos in Configurations/README
[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 /*
2443  * Test configuring the TLSv1.3 ciphersuites
2444  *
2445  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
2446  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
2447  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
2448  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
2449  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
2450  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
2451  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
2452  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
2453  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
2454  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
2455  */
2456 static int test_set_ciphersuite(int idx)
2457 {
2458     SSL_CTX *cctx = NULL, *sctx = NULL;
2459     SSL *clientssl = NULL, *serverssl = NULL;
2460     int testresult = 0;
2461
2462     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2463                                        TLS1_VERSION, TLS_MAX_VERSION,
2464                                        &sctx, &cctx, cert, privkey))
2465             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
2466                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
2467         goto end;
2468
2469     if (idx >=4 && idx <= 7) {
2470         /* SSL_CTX explicit cipher list */
2471         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
2472             goto end;
2473     }
2474
2475     if (idx == 0 || idx == 4) {
2476         /* Default ciphersuite */
2477         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2478                                                 "TLS_AES_128_GCM_SHA256")))
2479             goto end;
2480     } else if (idx == 1 || idx == 5) {
2481         /* Non default ciphersuite */
2482         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2483                                                 "TLS_AES_128_CCM_SHA256")))
2484             goto end;
2485     }
2486
2487     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2488                                           &clientssl, NULL, NULL)))
2489         goto end;
2490
2491     if (idx == 8 || idx == 9) {
2492         /* SSL explicit cipher list */
2493         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
2494             goto end;
2495     }
2496
2497     if (idx == 2 || idx == 6 || idx == 8) {
2498         /* Default ciphersuite */
2499         if (!TEST_true(SSL_set_ciphersuites(clientssl,
2500                                             "TLS_AES_128_GCM_SHA256")))
2501             goto end;
2502     } else if (idx == 3 || idx == 7 || idx == 9) {
2503         /* Non default ciphersuite */
2504         if (!TEST_true(SSL_set_ciphersuites(clientssl,
2505                                             "TLS_AES_128_CCM_SHA256")))
2506             goto end;
2507     }
2508
2509     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
2510         goto end;
2511
2512     testresult = 1;
2513
2514  end:
2515     SSL_free(serverssl);
2516     SSL_free(clientssl);
2517     SSL_CTX_free(sctx);
2518     SSL_CTX_free(cctx);
2519
2520     return testresult;
2521 }
2522
2523 static int test_ciphersuite_change(void)
2524 {
2525     SSL_CTX *cctx = NULL, *sctx = NULL;
2526     SSL *clientssl = NULL, *serverssl = NULL;
2527     SSL_SESSION *clntsess = NULL;
2528     int testresult = 0;
2529     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
2530
2531     /* Create a session based on SHA-256 */
2532     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2533                                        TLS1_VERSION, TLS_MAX_VERSION,
2534                                        &sctx, &cctx, cert, privkey))
2535             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
2536                                                    "TLS_AES_128_GCM_SHA256"))
2537             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2538                                           &clientssl, NULL, NULL))
2539             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2540                                                 SSL_ERROR_NONE)))
2541         goto end;
2542
2543     clntsess = SSL_get1_session(clientssl);
2544     /* Save for later */
2545     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
2546     SSL_shutdown(clientssl);
2547     SSL_shutdown(serverssl);
2548     SSL_free(serverssl);
2549     SSL_free(clientssl);
2550     serverssl = clientssl = NULL;
2551
2552 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
2553     /* Check we can resume a session with a different SHA-256 ciphersuite */
2554     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2555                                             "TLS_CHACHA20_POLY1305_SHA256"))
2556             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2557                                              NULL, NULL))
2558             || !TEST_true(SSL_set_session(clientssl, clntsess))
2559             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2560                                                 SSL_ERROR_NONE))
2561             || !TEST_true(SSL_session_reused(clientssl)))
2562         goto end;
2563
2564     SSL_SESSION_free(clntsess);
2565     clntsess = SSL_get1_session(clientssl);
2566     SSL_shutdown(clientssl);
2567     SSL_shutdown(serverssl);
2568     SSL_free(serverssl);
2569     SSL_free(clientssl);
2570     serverssl = clientssl = NULL;
2571 # endif
2572
2573     /*
2574      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
2575      * succeeds but does not resume.
2576      */
2577     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
2578             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2579                                              NULL, NULL))
2580             || !TEST_true(SSL_set_session(clientssl, clntsess))
2581             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2582                                                 SSL_ERROR_SSL))
2583             || !TEST_false(SSL_session_reused(clientssl)))
2584         goto end;
2585
2586     SSL_SESSION_free(clntsess);
2587     clntsess = NULL;
2588     SSL_shutdown(clientssl);
2589     SSL_shutdown(serverssl);
2590     SSL_free(serverssl);
2591     SSL_free(clientssl);
2592     serverssl = clientssl = NULL;
2593
2594     /* Create a session based on SHA384 */
2595     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
2596             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2597                                           &clientssl, NULL, NULL))
2598             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2599                                                 SSL_ERROR_NONE)))
2600         goto end;
2601
2602     clntsess = SSL_get1_session(clientssl);
2603     SSL_shutdown(clientssl);
2604     SSL_shutdown(serverssl);
2605     SSL_free(serverssl);
2606     SSL_free(clientssl);
2607     serverssl = clientssl = NULL;
2608
2609     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2610                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
2611             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
2612                                                    "TLS_AES_256_GCM_SHA384"))
2613             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2614                                              NULL, NULL))
2615             || !TEST_true(SSL_set_session(clientssl, clntsess))
2616                /*
2617                 * We use SSL_ERROR_WANT_READ below so that we can pause the
2618                 * connection after the initial ClientHello has been sent to
2619                 * enable us to make some session changes.
2620                 */
2621             || !TEST_false(create_ssl_connection(serverssl, clientssl,
2622                                                 SSL_ERROR_WANT_READ)))
2623         goto end;
2624
2625     /* Trick the client into thinking this session is for a different digest */
2626     clntsess->cipher = aes_128_gcm_sha256;
2627     clntsess->cipher_id = clntsess->cipher->id;
2628
2629     /*
2630      * Continue the previously started connection. Server has selected a SHA-384
2631      * ciphersuite, but client thinks the session is for SHA-256, so it should
2632      * bail out.
2633      */
2634     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
2635                                                 SSL_ERROR_SSL))
2636             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
2637                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
2638         goto end;
2639
2640     testresult = 1;
2641
2642  end:
2643     SSL_SESSION_free(clntsess);
2644     SSL_free(serverssl);
2645     SSL_free(clientssl);
2646     SSL_CTX_free(sctx);
2647     SSL_CTX_free(cctx);
2648
2649     return testresult;
2650 }
2651
2652 static int test_tls13_psk(int idx)
2653 {
2654     SSL_CTX *sctx = NULL, *cctx = NULL;
2655     SSL *serverssl = NULL, *clientssl = NULL;
2656     const SSL_CIPHER *cipher = NULL;
2657     const unsigned char key[] = {
2658         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
2659         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
2660         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
2661         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
2662     };
2663     int testresult = 0;
2664
2665     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2666                                        TLS1_VERSION, TLS_MAX_VERSION,
2667                                        &sctx, &cctx, cert, privkey)))
2668         goto end;
2669
2670     /*
2671      * We use a ciphersuite with SHA256 to ease testing old style PSK callbacks
2672      * which will always default to SHA256
2673      */
2674     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256")))
2675         goto end;
2676
2677     /*
2678      * Test 0: New style callbacks only
2679      * Test 1: New and old style callbacks (only the new ones should be used)
2680      * Test 2: Old style callbacks only
2681      */
2682     if (idx == 0 || idx == 1) {
2683         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2684         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2685     }
2686 #ifndef OPENSSL_NO_PSK
2687     if (idx == 1 || idx == 2) {
2688         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
2689         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
2690     }
2691 #endif
2692     srvid = pskid;
2693     use_session_cb_cnt = 0;
2694     find_session_cb_cnt = 0;
2695     psk_client_cb_cnt = 0;
2696     psk_server_cb_cnt = 0;
2697
2698     /* Check we can create a connection if callback decides not to send a PSK */
2699     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2700                                              NULL, NULL))
2701             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2702                                                 SSL_ERROR_NONE))
2703             || !TEST_false(SSL_session_reused(clientssl))
2704             || !TEST_false(SSL_session_reused(serverssl)))
2705         goto end;
2706
2707     if (idx == 0 || idx == 1) {
2708         if (!TEST_true(use_session_cb_cnt == 1)
2709                 || !TEST_true(find_session_cb_cnt == 0)
2710                    /*
2711                     * If no old style callback then below should be 0
2712                     * otherwise 1
2713                     */
2714                 || !TEST_true(psk_client_cb_cnt == idx)
2715                 || !TEST_true(psk_server_cb_cnt == 0))
2716             goto end;
2717     } else {
2718         if (!TEST_true(use_session_cb_cnt == 0)
2719                 || !TEST_true(find_session_cb_cnt == 0)
2720                 || !TEST_true(psk_client_cb_cnt == 1)
2721                 || !TEST_true(psk_server_cb_cnt == 0))
2722             goto end;
2723     }
2724
2725     shutdown_ssl_connection(serverssl, clientssl);
2726     serverssl = clientssl = NULL;
2727     use_session_cb_cnt = psk_client_cb_cnt = 0;
2728
2729     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2730                                              NULL, NULL)))
2731         goto end;
2732
2733     /* Create the PSK */
2734     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
2735     clientpsk = SSL_SESSION_new();
2736     if (!TEST_ptr(clientpsk)
2737             || !TEST_ptr(cipher)
2738             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
2739                                                       sizeof(key)))
2740             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
2741             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
2742                                                            TLS1_3_VERSION))
2743             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
2744         goto end;
2745     serverpsk = clientpsk;
2746
2747     /* Check we can create a connection and the PSK is used */
2748     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2749             || !TEST_true(SSL_session_reused(clientssl))
2750             || !TEST_true(SSL_session_reused(serverssl)))
2751         goto end;
2752
2753     if (idx == 0 || idx == 1) {
2754         if (!TEST_true(use_session_cb_cnt == 1)
2755                 || !TEST_true(find_session_cb_cnt == 1)
2756                 || !TEST_true(psk_client_cb_cnt == 0)
2757                 || !TEST_true(psk_server_cb_cnt == 0))
2758             goto end;
2759     } else {
2760         if (!TEST_true(use_session_cb_cnt == 0)
2761                 || !TEST_true(find_session_cb_cnt == 0)
2762                 || !TEST_true(psk_client_cb_cnt == 1)
2763                 || !TEST_true(psk_server_cb_cnt == 1))
2764             goto end;
2765     }
2766
2767     shutdown_ssl_connection(serverssl, clientssl);
2768     serverssl = clientssl = NULL;
2769     use_session_cb_cnt = find_session_cb_cnt = 0;
2770     psk_client_cb_cnt = psk_server_cb_cnt = 0;
2771
2772     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2773                                              NULL, NULL)))
2774         goto end;
2775
2776     /* Force an HRR */
2777     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2778         goto end;
2779
2780     /*
2781      * Check we can create a connection, the PSK is used and the callbacks are
2782      * called twice.
2783      */
2784     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2785             || !TEST_true(SSL_session_reused(clientssl))
2786             || !TEST_true(SSL_session_reused(serverssl)))
2787         goto end;
2788
2789     if (idx == 0 || idx == 1) {
2790         if (!TEST_true(use_session_cb_cnt == 2)
2791                 || !TEST_true(find_session_cb_cnt == 2)
2792                 || !TEST_true(psk_client_cb_cnt == 0)
2793                 || !TEST_true(psk_server_cb_cnt == 0))
2794             goto end;
2795     } else {
2796         if (!TEST_true(use_session_cb_cnt == 0)
2797                 || !TEST_true(find_session_cb_cnt == 0)
2798                 || !TEST_true(psk_client_cb_cnt == 2)
2799                 || !TEST_true(psk_server_cb_cnt == 2))
2800             goto end;
2801     }
2802
2803     shutdown_ssl_connection(serverssl, clientssl);
2804     serverssl = clientssl = NULL;
2805     use_session_cb_cnt = find_session_cb_cnt = 0;
2806     psk_client_cb_cnt = psk_server_cb_cnt = 0;
2807
2808     /*
2809      * Check that if the server rejects the PSK we can still connect, but with
2810      * a full handshake
2811      */
2812     srvid = "Dummy Identity";
2813     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2814                                              NULL, NULL))
2815             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2816                                                 SSL_ERROR_NONE))
2817             || !TEST_false(SSL_session_reused(clientssl))
2818             || !TEST_false(SSL_session_reused(serverssl)))
2819         goto end;
2820
2821     if (idx == 0 || idx == 1) {
2822         if (!TEST_true(use_session_cb_cnt == 1)
2823                 || !TEST_true(find_session_cb_cnt == 1)
2824                 || !TEST_true(psk_client_cb_cnt == 0)
2825                    /*
2826                     * If no old style callback then below should be 0
2827                     * otherwise 1
2828                     */
2829                 || !TEST_true(psk_server_cb_cnt == idx))
2830             goto end;
2831     } else {
2832         if (!TEST_true(use_session_cb_cnt == 0)
2833                 || !TEST_true(find_session_cb_cnt == 0)
2834                 || !TEST_true(psk_client_cb_cnt == 1)
2835                 || !TEST_true(psk_server_cb_cnt == 1))
2836             goto end;
2837     }
2838
2839     shutdown_ssl_connection(serverssl, clientssl);
2840     serverssl = clientssl = NULL;
2841     testresult = 1;
2842
2843  end:
2844     SSL_SESSION_free(clientpsk);
2845     SSL_SESSION_free(serverpsk);
2846     clientpsk = serverpsk = NULL;
2847     SSL_free(serverssl);
2848     SSL_free(clientssl);
2849     SSL_CTX_free(sctx);
2850     SSL_CTX_free(cctx);
2851     return testresult;
2852 }
2853
2854 static unsigned char cookie_magic_value[] = "cookie magic";
2855
2856 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
2857                                     unsigned int *cookie_len)
2858 {
2859     /*
2860      * Not suitable as a real cookie generation function but good enough for
2861      * testing!
2862      */
2863     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
2864     *cookie_len = sizeof(cookie_magic_value) - 1;
2865
2866     return 1;
2867 }
2868
2869 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
2870                                   unsigned int cookie_len)
2871 {
2872     if (cookie_len == sizeof(cookie_magic_value) - 1
2873         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
2874         return 1;
2875
2876     return 0;
2877 }
2878
2879 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
2880                                         size_t *cookie_len)
2881 {
2882     unsigned int temp;
2883     int res = generate_cookie_callback(ssl, cookie, &temp);
2884     *cookie_len = temp;
2885     return res;
2886 }
2887
2888 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
2889                                       size_t cookie_len)
2890 {
2891     return verify_cookie_callback(ssl, cookie, cookie_len);
2892 }
2893
2894 static int test_stateless(void)
2895 {
2896     SSL_CTX *sctx = NULL, *cctx = NULL;
2897     SSL *serverssl = NULL, *clientssl = NULL;
2898     int testresult = 0;
2899
2900     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2901                                        TLS1_VERSION, TLS_MAX_VERSION,
2902                                        &sctx, &cctx, cert, privkey)))
2903         goto end;
2904
2905     /* The arrival of CCS messages can confuse the test */
2906     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
2907
2908     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2909                                       NULL, NULL))
2910                /* Send the first ClientHello */
2911             || !TEST_false(create_ssl_connection(serverssl, clientssl,
2912                                                  SSL_ERROR_WANT_READ))
2913                /*
2914                 * This should fail with a -1 return because we have no callbacks
2915                 * set up
2916                 */
2917             || !TEST_int_eq(SSL_stateless(serverssl), -1))
2918         goto end;
2919
2920     /* Fatal error so abandon the connection from this client */
2921     SSL_free(clientssl);
2922     clientssl = NULL;
2923
2924     /* Set up the cookie generation and verification callbacks */
2925     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
2926     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
2927
2928     /*
2929      * Create a new connection from the client (we can reuse the server SSL
2930      * object).
2931      */
2932     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2933                                              NULL, NULL))
2934                /* Send the first ClientHello */
2935             || !TEST_false(create_ssl_connection(serverssl, clientssl,
2936                                                 SSL_ERROR_WANT_READ))
2937                /* This should fail because there is no cookie */
2938             || !TEST_int_eq(SSL_stateless(serverssl), 0))
2939         goto end;
2940
2941     /* Abandon the connection from this client */
2942     SSL_free(clientssl);
2943     clientssl = NULL;
2944
2945     /*
2946      * Now create a connection from a new client but with the same server SSL
2947      * object
2948      */
2949     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2950                                              NULL, NULL))
2951                /* Send the first ClientHello */
2952             || !TEST_false(create_ssl_connection(serverssl, clientssl,
2953                                                 SSL_ERROR_WANT_READ))
2954                /* This should fail because there is no cookie */
2955             || !TEST_int_eq(SSL_stateless(serverssl), 0)
2956                /* Send the second ClientHello */
2957             || !TEST_false(create_ssl_connection(serverssl, clientssl,
2958                                                 SSL_ERROR_WANT_READ))
2959                /* This should succeed because a cookie is now present */
2960             || !TEST_int_eq(SSL_stateless(serverssl), 1)
2961                /* Complete the connection */
2962             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2963                                                 SSL_ERROR_NONE)))
2964         goto end;
2965
2966     shutdown_ssl_connection(serverssl, clientssl);
2967     serverssl = clientssl = NULL;
2968     testresult = 1;
2969
2970  end:
2971     SSL_free(serverssl);
2972     SSL_free(clientssl);
2973     SSL_CTX_free(sctx);
2974     SSL_CTX_free(cctx);
2975     return testresult;
2976
2977 }
2978 #endif /* OPENSSL_NO_TLS1_3 */
2979
2980 static int clntaddoldcb = 0;
2981 static int clntparseoldcb = 0;
2982 static int srvaddoldcb = 0;
2983 static int srvparseoldcb = 0;
2984 static int clntaddnewcb = 0;
2985 static int clntparsenewcb = 0;
2986 static int srvaddnewcb = 0;
2987 static int srvparsenewcb = 0;
2988 static int snicb = 0;
2989
2990 #define TEST_EXT_TYPE1  0xff00
2991
2992 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
2993                       size_t *outlen, int *al, void *add_arg)
2994 {
2995     int *server = (int *)add_arg;
2996     unsigned char *data;
2997
2998     if (SSL_is_server(s))
2999         srvaddoldcb++;
3000     else
3001         clntaddoldcb++;
3002
3003     if (*server != SSL_is_server(s)
3004             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3005         return -1;
3006
3007     *data = 1;
3008     *out = data;
3009     *outlen = sizeof(char);
3010     return 1;
3011 }
3012
3013 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
3014                         void *add_arg)
3015 {
3016     OPENSSL_free((unsigned char *)out);
3017 }
3018
3019 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
3020                         size_t inlen, int *al, void *parse_arg)
3021 {
3022     int *server = (int *)parse_arg;
3023
3024     if (SSL_is_server(s))
3025         srvparseoldcb++;
3026     else
3027         clntparseoldcb++;
3028
3029     if (*server != SSL_is_server(s)
3030             || inlen != sizeof(char)
3031             || *in != 1)
3032         return -1;
3033
3034     return 1;
3035 }
3036
3037 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
3038                       const unsigned char **out, size_t *outlen, X509 *x,
3039                       size_t chainidx, int *al, void *add_arg)
3040 {
3041     int *server = (int *)add_arg;
3042     unsigned char *data;
3043
3044     if (SSL_is_server(s))
3045         srvaddnewcb++;
3046     else
3047         clntaddnewcb++;
3048
3049     if (*server != SSL_is_server(s)
3050             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3051         return -1;
3052
3053     *data = 1;
3054     *out = data;
3055     *outlen = sizeof(*data);
3056     return 1;
3057 }
3058
3059 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
3060                         const unsigned char *out, void *add_arg)
3061 {
3062     OPENSSL_free((unsigned char *)out);
3063 }
3064
3065 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
3066                         const unsigned char *in, size_t inlen, X509 *x,
3067                         size_t chainidx, int *al, void *parse_arg)
3068 {
3069     int *server = (int *)parse_arg;
3070
3071     if (SSL_is_server(s))
3072         srvparsenewcb++;
3073     else
3074         clntparsenewcb++;
3075
3076     if (*server != SSL_is_server(s)
3077             || inlen != sizeof(char) || *in != 1)
3078         return -1;
3079
3080     return 1;
3081 }
3082
3083 static int sni_cb(SSL *s, int *al, void *arg)
3084 {
3085     SSL_CTX *ctx = (SSL_CTX *)arg;
3086
3087     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
3088         *al = SSL_AD_INTERNAL_ERROR;
3089         return SSL_TLSEXT_ERR_ALERT_FATAL;
3090     }
3091     snicb++;
3092     return SSL_TLSEXT_ERR_OK;
3093 }
3094
3095 /*
3096  * Custom call back tests.
3097  * Test 0: Old style callbacks in TLSv1.2
3098  * Test 1: New style callbacks in TLSv1.2
3099  * Test 2: New style callbacks in TLSv1.2 with SNI
3100  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
3101  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
3102  */
3103 static int test_custom_exts(int tst)
3104 {
3105     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
3106     SSL *clientssl = NULL, *serverssl = NULL;
3107     int testresult = 0;
3108     static int server = 1;
3109     static int client = 0;
3110     SSL_SESSION *sess = NULL;
3111     unsigned int context;
3112
3113 #if defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_3)
3114     /* Skip tests for TLSv1.2 and below in this case */
3115     if (tst < 3)
3116         return 1;
3117 #endif
3118
3119     /* Reset callback counters */
3120     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
3121     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
3122     snicb = 0;
3123
3124     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3125                                        TLS1_VERSION, TLS_MAX_VERSION,
3126                                        &sctx, &cctx, cert, privkey)))
3127         goto end;
3128
3129     if (tst == 2
3130             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL,
3131                                               TLS1_VERSION, TLS_MAX_VERSION,
3132                                               &sctx2, NULL, cert, privkey)))
3133         goto end;
3134
3135
3136     if (tst < 3) {
3137         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
3138         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
3139         if (sctx2 != NULL)
3140             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
3141     }
3142
3143     if (tst == 4) {
3144         context = SSL_EXT_CLIENT_HELLO
3145                   | SSL_EXT_TLS1_2_SERVER_HELLO
3146                   | SSL_EXT_TLS1_3_SERVER_HELLO
3147                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
3148                   | SSL_EXT_TLS1_3_CERTIFICATE
3149                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
3150     } else {
3151         context = SSL_EXT_CLIENT_HELLO
3152                   | SSL_EXT_TLS1_2_SERVER_HELLO
3153                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
3154     }
3155
3156     /* Create a client side custom extension */
3157     if (tst == 0) {
3158         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3159                                                      old_add_cb, old_free_cb,
3160                                                      &client, old_parse_cb,
3161                                                      &client)))
3162             goto end;
3163     } else {
3164         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
3165                                               new_add_cb, new_free_cb,
3166                                               &client, new_parse_cb, &client)))
3167             goto end;
3168     }
3169
3170     /* Should not be able to add duplicates */
3171     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3172                                                   old_add_cb, old_free_cb,
3173                                                   &client, old_parse_cb,
3174                                                   &client))
3175             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
3176                                                   context, new_add_cb,
3177                                                   new_free_cb, &client,
3178                                                   new_parse_cb, &client)))
3179         goto end;
3180
3181     /* Create a server side custom extension */
3182     if (tst == 0) {
3183         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3184                                                      old_add_cb, old_free_cb,
3185                                                      &server, old_parse_cb,
3186                                                      &server)))
3187             goto end;
3188     } else {
3189         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
3190                                               new_add_cb, new_free_cb,
3191                                               &server, new_parse_cb, &server)))
3192             goto end;
3193         if (sctx2 != NULL
3194                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
3195                                                      context, new_add_cb,
3196                                                      new_free_cb, &server,
3197                                                      new_parse_cb, &server)))
3198             goto end;
3199     }
3200
3201     /* Should not be able to add duplicates */
3202     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3203                                                   old_add_cb, old_free_cb,
3204                                                   &server, old_parse_cb,
3205                                                   &server))
3206             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
3207                                                   context, new_add_cb,
3208                                                   new_free_cb, &server,
3209                                                   new_parse_cb, &server)))
3210         goto end;
3211
3212     if (tst == 2) {
3213         /* Set up SNI */
3214         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
3215                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
3216             goto end;
3217     }
3218
3219     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3220                                       &clientssl, NULL, NULL))
3221             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3222                                                 SSL_ERROR_NONE)))
3223         goto end;
3224
3225     if (tst == 0) {
3226         if (clntaddoldcb != 1
3227                 || clntparseoldcb != 1
3228                 || srvaddoldcb != 1
3229                 || srvparseoldcb != 1)
3230             goto end;
3231     } else if (tst == 1 || tst == 2 || tst == 3) {
3232         if (clntaddnewcb != 1
3233                 || clntparsenewcb != 1
3234                 || srvaddnewcb != 1
3235                 || srvparsenewcb != 1
3236                 || (tst != 2 && snicb != 0)
3237                 || (tst == 2 && snicb != 1))
3238             goto end;
3239     } else {
3240         if (clntaddnewcb != 1
3241                 || clntparsenewcb != 4
3242                 || srvaddnewcb != 4
3243                 || srvparsenewcb != 1)
3244             goto end;
3245     }
3246
3247     sess = SSL_get1_session(clientssl);
3248     SSL_shutdown(clientssl);
3249     SSL_shutdown(serverssl);
3250     SSL_free(serverssl);
3251     SSL_free(clientssl);
3252     serverssl = clientssl = NULL;
3253
3254     if (tst == 3) {
3255         /* We don't bother with the resumption aspects for this test */
3256         testresult = 1;
3257         goto end;
3258     }
3259
3260     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3261                                       NULL, NULL))
3262             || !TEST_true(SSL_set_session(clientssl, sess))
3263             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3264                                                SSL_ERROR_NONE)))
3265         goto end;
3266
3267     /*
3268      * For a resumed session we expect to add the ClientHello extension. For the
3269      * old style callbacks we ignore it on the server side because they set
3270      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
3271      * them.
3272      */
3273     if (tst == 0) {
3274         if (clntaddoldcb != 2
3275                 || clntparseoldcb != 1
3276                 || srvaddoldcb != 1
3277                 || srvparseoldcb != 1)
3278             goto end;
3279     } else if (tst == 1 || tst == 2 || tst == 3) {
3280         if (clntaddnewcb != 2
3281                 || clntparsenewcb != 2
3282                 || srvaddnewcb != 2
3283                 || srvparsenewcb != 2)
3284             goto end;
3285     } else {
3286         /* No Certificate message extensions in the resumption handshake */
3287         if (clntaddnewcb != 2
3288                 || clntparsenewcb != 7
3289                 || srvaddnewcb != 7
3290                 || srvparsenewcb != 2)
3291             goto end;
3292     }
3293
3294     testresult = 1;
3295
3296 end:
3297     SSL_SESSION_free(sess);
3298     SSL_free(serverssl);
3299     SSL_free(clientssl);
3300     SSL_CTX_free(sctx2);
3301     SSL_CTX_free(sctx);
3302     SSL_CTX_free(cctx);
3303     return testresult;
3304 }
3305
3306 /*
3307  * Test loading of serverinfo data in various formats. test_sslmessages actually
3308  * tests to make sure the extensions appear in the handshake
3309  */
3310 static int test_serverinfo(int tst)
3311 {
3312     unsigned int version;
3313     unsigned char *sibuf;
3314     size_t sibuflen;
3315     int ret, expected, testresult = 0;
3316     SSL_CTX *ctx;
3317
3318     ctx = SSL_CTX_new(TLS_method());
3319     if (!TEST_ptr(ctx))
3320         goto end;
3321
3322     if ((tst & 0x01) == 0x01)
3323         version = SSL_SERVERINFOV2;
3324     else
3325         version = SSL_SERVERINFOV1;
3326
3327     if ((tst & 0x02) == 0x02) {
3328         sibuf = serverinfov2;
3329         sibuflen = sizeof(serverinfov2);
3330         expected = (version == SSL_SERVERINFOV2);
3331     } else {
3332         sibuf = serverinfov1;
3333         sibuflen = sizeof(serverinfov1);
3334         expected = (version == SSL_SERVERINFOV1);
3335     }
3336
3337     if ((tst & 0x04) == 0x04) {
3338         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
3339     } else {
3340         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
3341
3342         /*
3343          * The version variable is irrelevant in this case - it's what is in the
3344          * buffer that matters
3345          */
3346         if ((tst & 0x02) == 0x02)
3347             expected = 0;
3348         else
3349             expected = 1;
3350     }
3351
3352     if (!TEST_true(ret == expected))
3353         goto end;
3354
3355     testresult = 1;
3356
3357  end:
3358     SSL_CTX_free(ctx);
3359
3360     return testresult;
3361 }
3362
3363 /*
3364  * Test that SSL_export_keying_material() produces expected results. There are
3365  * no test vectors so all we do is test that both sides of the communication
3366  * produce the same results for different protocol versions.
3367  */
3368 static int test_export_key_mat(int tst)
3369 {
3370     int testresult = 0;
3371     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
3372     SSL *clientssl = NULL, *serverssl = NULL;
3373     const char label[] = "test label";
3374     const unsigned char context[] = "context";
3375     const unsigned char *emptycontext = NULL;
3376     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
3377     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
3378     const int protocols[] = {
3379         TLS1_VERSION,
3380         TLS1_1_VERSION,
3381         TLS1_2_VERSION,
3382         TLS1_3_VERSION
3383     };
3384
3385 #ifdef OPENSSL_NO_TLS1
3386     if (tst == 0)
3387         return 1;
3388 #endif
3389 #ifdef OPENSSL_NO_TLS1_1
3390     if (tst == 1)
3391         return 1;
3392 #endif
3393 #ifdef OPENSSL_NO_TLS1_2
3394     if (tst == 2)
3395         return 1;
3396 #endif
3397 #ifdef OPENSSL_NO_TLS1_3
3398     if (tst == 3)
3399         return 1;
3400 #endif
3401     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3402                                        TLS1_VERSION, TLS_MAX_VERSION,
3403                                        &sctx, &cctx, cert, privkey)))
3404         goto end;
3405
3406     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
3407     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
3408     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
3409
3410     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
3411                                       NULL))
3412             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3413                                                 SSL_ERROR_NONE)))
3414         goto end;
3415
3416     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
3417                                                 sizeof(ckeymat1), label,
3418                                                 sizeof(label) - 1, context,
3419                                                 sizeof(context) - 1, 1), 1)
3420             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
3421                                                        sizeof(ckeymat2), label,
3422                                                        sizeof(label) - 1,
3423                                                        emptycontext,
3424                                                        0, 1), 1)
3425             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
3426                                                        sizeof(ckeymat3), label,
3427                                                        sizeof(label) - 1,
3428                                                        NULL, 0, 0), 1)
3429             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
3430                                                        sizeof(skeymat1), label,
3431                                                        sizeof(label) - 1,
3432                                                        context,
3433                                                        sizeof(context) -1, 1),
3434                             1)
3435             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
3436                                                        sizeof(skeymat2), label,
3437                                                        sizeof(label) - 1,
3438                                                        emptycontext,
3439                                                        0, 1), 1)
3440             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
3441                                                        sizeof(skeymat3), label,
3442                                                        sizeof(label) - 1,
3443                                                        NULL, 0, 0), 1)
3444                /*
3445                 * Check that both sides created the same key material with the
3446                 * same context.
3447                 */
3448             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
3449                             sizeof(skeymat1))
3450                /*
3451                 * Check that both sides created the same key material with an
3452                 * empty context.
3453                 */
3454             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
3455                             sizeof(skeymat2))
3456                /*
3457                 * Check that both sides created the same key material without a
3458                 * context.
3459                 */
3460             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
3461                             sizeof(skeymat3))
3462                /* Different contexts should produce different results */
3463             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
3464                             sizeof(ckeymat2)))
3465         goto end;
3466
3467     /*
3468      * Check that an empty context and no context produce different results in
3469      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
3470      */
3471     if ((tst != 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
3472                                   sizeof(ckeymat3)))
3473             || (tst ==3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
3474                                         sizeof(ckeymat3))))
3475         goto end;
3476
3477     testresult = 1;
3478
3479  end:
3480     SSL_free(serverssl);
3481     SSL_free(clientssl);
3482     SSL_CTX_free(sctx2);
3483     SSL_CTX_free(sctx);
3484     SSL_CTX_free(cctx);
3485
3486     return testresult;
3487 }
3488
3489 #ifndef OPENSSL_NO_TLS1_3
3490 /*
3491  * Test that SSL_export_keying_material_early() produces expected
3492  * results. There are no test vectors so all we do is test that both
3493  * sides of the communication produce the same results for different
3494  * protocol versions.
3495  */
3496 static int test_export_key_mat_early(int idx)
3497 {
3498     static const char label[] = "test label";
3499     static const unsigned char context[] = "context";
3500     int testresult = 0;
3501     SSL_CTX *cctx = NULL, *sctx = NULL;
3502     SSL *clientssl = NULL, *serverssl = NULL;
3503     SSL_SESSION *sess = NULL;
3504     const unsigned char *emptycontext = NULL;
3505     unsigned char ckeymat1[80], ckeymat2[80];
3506     unsigned char skeymat1[80], skeymat2[80];
3507     unsigned char buf[1];
3508     size_t readbytes, written;
3509
3510     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
3511                                         &sess, idx)))
3512         goto end;
3513
3514     /* Here writing 0 length early data is enough. */
3515     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
3516             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3517                                                 &readbytes),
3518                             SSL_READ_EARLY_DATA_ERROR)
3519             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3520                             SSL_EARLY_DATA_ACCEPTED))
3521         goto end;
3522
3523     if (!TEST_int_eq(SSL_export_keying_material_early(
3524                      clientssl, ckeymat1, sizeof(ckeymat1), label,
3525                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
3526             || !TEST_int_eq(SSL_export_keying_material_early(
3527                             clientssl, ckeymat2, sizeof(ckeymat2), label,
3528                             sizeof(label) - 1, emptycontext, 0), 1)
3529             || !TEST_int_eq(SSL_export_keying_material_early(
3530                             serverssl, skeymat1, sizeof(skeymat1), label,
3531                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
3532             || !TEST_int_eq(SSL_export_keying_material_early(
3533                             serverssl, skeymat2, sizeof(skeymat2), label,
3534                             sizeof(label) - 1, emptycontext, 0), 1)
3535                /*
3536                 * Check that both sides created the same key material with the
3537                 * same context.
3538                 */
3539             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
3540                             sizeof(skeymat1))
3541                /*
3542                 * Check that both sides created the same key material with an
3543                 * empty context.
3544                 */
3545             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
3546                             sizeof(skeymat2))
3547                /* Different contexts should produce different results */
3548             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
3549                             sizeof(ckeymat2)))
3550         goto end;
3551
3552     testresult = 1;
3553
3554  end:
3555     if (sess != clientpsk)
3556         SSL_SESSION_free(sess);
3557     SSL_SESSION_free(clientpsk);
3558     SSL_SESSION_free(serverpsk);
3559     clientpsk = serverpsk = NULL;
3560     SSL_free(serverssl);
3561     SSL_free(clientssl);
3562     SSL_CTX_free(sctx);
3563     SSL_CTX_free(cctx);
3564
3565     return testresult;
3566 }
3567 #endif /* OPENSSL_NO_TLS1_3 */
3568
3569 static int test_ssl_clear(int idx)
3570 {
3571     SSL_CTX *cctx = NULL, *sctx = NULL;
3572     SSL *clientssl = NULL, *serverssl = NULL;
3573     int testresult = 0;
3574
3575 #ifdef OPENSSL_NO_TLS1_2
3576     if (idx == 1)
3577         return 1;
3578 #endif
3579
3580     /* Create an initial connection */
3581     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3582                                        TLS1_VERSION, TLS_MAX_VERSION,
3583                                        &sctx, &cctx, cert, privkey))
3584             || (idx == 1
3585                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
3586                                                             TLS1_2_VERSION)))
3587             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3588                                           &clientssl, NULL, NULL))
3589             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3590                                                 SSL_ERROR_NONE)))
3591         goto end;
3592
3593     SSL_shutdown(clientssl);
3594     SSL_shutdown(serverssl);
3595     SSL_free(serverssl);
3596     serverssl = NULL;
3597
3598     /* Clear clientssl - we're going to reuse the object */
3599     if (!TEST_true(SSL_clear(clientssl)))
3600         goto end;
3601
3602     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3603                                              NULL, NULL))
3604             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3605                                                 SSL_ERROR_NONE))
3606             || !TEST_true(SSL_session_reused(clientssl)))
3607         goto end;
3608
3609     SSL_shutdown(clientssl);
3610     SSL_shutdown(serverssl);
3611
3612     testresult = 1;
3613
3614  end:
3615     SSL_free(serverssl);
3616     SSL_free(clientssl);
3617     SSL_CTX_free(sctx);
3618     SSL_CTX_free(cctx);
3619
3620     return testresult;
3621 }
3622
3623 /* Parse CH and retrieve any MFL extension value if present */
3624 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
3625 {
3626     long len;
3627     unsigned char *data;
3628     PACKET pkt = {0}, pkt2 = {0}, pkt3 = {0};
3629     unsigned int MFL_code = 0, type = 0;
3630
3631     if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
3632         goto end;
3633
3634     if (!TEST_true( PACKET_buf_init( &pkt, data, len ) )
3635                /* Skip the record header */
3636             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
3637                /* Skip the handshake message header */
3638             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
3639                /* Skip client version and random */
3640             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
3641                                                + SSL3_RANDOM_SIZE))
3642                /* Skip session id */
3643             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
3644                /* Skip ciphers */
3645             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
3646                /* Skip compression */
3647             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
3648                /* Extensions len */
3649             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
3650         goto end;
3651
3652     /* Loop through all extensions */
3653     while (PACKET_remaining(&pkt2)) {
3654         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
3655                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
3656             goto end;
3657
3658         if (type == TLSEXT_TYPE_max_fragment_length) {
3659             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
3660                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
3661                 goto end;
3662
3663             *mfl_codemfl_code = MFL_code;
3664             return 1;
3665         }
3666     }
3667
3668  end:
3669     return 0;
3670 }
3671
3672 /* Maximum-Fragment-Length TLS extension mode to test */
3673 static const unsigned char max_fragment_len_test[] = {
3674     TLSEXT_max_fragment_length_512,
3675     TLSEXT_max_fragment_length_1024,
3676     TLSEXT_max_fragment_length_2048,
3677     TLSEXT_max_fragment_length_4096
3678 };
3679
3680 static int test_max_fragment_len_ext(int idx_tst)
3681 {
3682     SSL_CTX *ctx;
3683     SSL *con = NULL;
3684     int testresult = 0, MFL_mode = 0;
3685     BIO *rbio, *wbio;
3686
3687     ctx = SSL_CTX_new(TLS_method());
3688     if (!TEST_ptr(ctx))
3689         goto end;
3690
3691     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
3692                    ctx, max_fragment_len_test[idx_tst])))
3693         goto end;
3694
3695     con = SSL_new(ctx);
3696     if (!TEST_ptr(con))
3697         goto end;
3698
3699     rbio = BIO_new(BIO_s_mem());
3700     wbio = BIO_new(BIO_s_mem());
3701     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
3702         BIO_free(rbio);
3703         BIO_free(wbio);
3704         goto end;
3705     }
3706
3707     SSL_set_bio(con, rbio, wbio);
3708     SSL_set_connect_state(con);
3709
3710     if (!TEST_int_le(SSL_connect(con), 0)) {
3711         /* This shouldn't succeed because we don't have a server! */
3712         goto end;
3713     }
3714
3715     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
3716         /* no MFL in client hello */
3717         goto end;
3718     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
3719         goto end;
3720
3721     testresult = 1;
3722
3723 end:
3724     SSL_free(con);
3725     SSL_CTX_free(ctx);
3726
3727     return testresult;
3728 }
3729
3730 #ifndef OPENSSL_NO_TLS1_3
3731 static int test_pha_key_update(void)
3732 {
3733     SSL_CTX *cctx = NULL, *sctx = NULL;
3734     SSL *clientssl = NULL, *serverssl = NULL;
3735     int testresult = 0;
3736
3737     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3738                                        TLS1_VERSION, TLS_MAX_VERSION,
3739                                        &sctx, &cctx, cert, privkey)))
3740         return 0;
3741
3742     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
3743         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
3744         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
3745         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
3746         goto end;
3747
3748
3749     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3750                                       NULL, NULL)))
3751         goto end;
3752
3753     SSL_force_post_handshake_auth(clientssl);
3754
3755     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
3756                                          SSL_ERROR_NONE)))
3757         goto end;
3758
3759     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
3760     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
3761         goto end;
3762
3763     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
3764         goto end;
3765
3766     /* Start handshake on the server */
3767     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
3768         goto end;
3769
3770     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
3771     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
3772                                          SSL_ERROR_NONE)))
3773         goto end;
3774
3775     SSL_shutdown(clientssl);
3776     SSL_shutdown(serverssl);
3777
3778     testresult = 1;
3779
3780  end:
3781     SSL_free(serverssl);
3782     SSL_free(clientssl);
3783     SSL_CTX_free(sctx);
3784     SSL_CTX_free(cctx);
3785     return testresult;
3786 }
3787 #endif
3788
3789 int setup_tests(void)
3790 {
3791     if (!TEST_ptr(cert = test_get_argument(0))
3792             || !TEST_ptr(privkey = test_get_argument(1)))
3793         return 0;
3794
3795     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
3796 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
3797         TEST_error("not supported in this build");
3798         return 0;
3799 #else
3800         int i, mcount, rcount, fcount;
3801
3802         for (i = 0; i < 4; i++)
3803             test_export_key_mat(i);
3804         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
3805         test_printf_stdout("malloc %d realloc %d free %d\n",
3806                 mcount, rcount, fcount);
3807         return 1;
3808 #endif
3809     }
3810
3811     ADD_TEST(test_large_message_tls);
3812     ADD_TEST(test_large_message_tls_read_ahead);
3813 #ifndef OPENSSL_NO_DTLS
3814     ADD_TEST(test_large_message_dtls);
3815 #endif
3816 #ifndef OPENSSL_NO_OCSP
3817     ADD_TEST(test_tlsext_status_type);
3818 #endif
3819     ADD_TEST(test_session_with_only_int_cache);
3820     ADD_TEST(test_session_with_only_ext_cache);
3821     ADD_TEST(test_session_with_both_cache);
3822     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
3823     ADD_TEST(test_ssl_bio_pop_next_bio);
3824     ADD_TEST(test_ssl_bio_pop_ssl_bio);
3825     ADD_TEST(test_ssl_bio_change_rbio);
3826     ADD_TEST(test_ssl_bio_change_wbio);
3827 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
3828     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
3829     ADD_TEST(test_keylog);
3830 #endif
3831 #ifndef OPENSSL_NO_TLS1_3
3832     ADD_TEST(test_keylog_no_master_key);
3833 #endif
3834 #ifndef OPENSSL_NO_TLS1_2
3835     ADD_TEST(test_client_hello_cb);
3836 #endif
3837 #ifndef OPENSSL_NO_TLS1_3
3838     ADD_ALL_TESTS(test_early_data_read_write, 3);
3839     /*
3840      * We don't do replay tests for external PSK. Replay protection isn't used
3841      * in that scenario.
3842      */
3843     ADD_ALL_TESTS(test_early_data_replay, 2);
3844     ADD_ALL_TESTS(test_early_data_skip, 3);
3845     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
3846     ADD_ALL_TESTS(test_early_data_not_sent, 3);
3847     ADD_ALL_TESTS(test_early_data_psk, 8);
3848     ADD_ALL_TESTS(test_early_data_not_expected, 3);
3849 # ifndef OPENSSL_NO_TLS1_2
3850     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
3851 # endif
3852 #endif
3853 #ifndef OPENSSL_NO_TLS1_3
3854     ADD_ALL_TESTS(test_set_ciphersuite, 10);
3855     ADD_TEST(test_ciphersuite_change);
3856 #ifdef OPENSSL_NO_PSK
3857     ADD_ALL_TESTS(test_tls13_psk, 1);
3858 #else
3859     ADD_ALL_TESTS(test_tls13_psk, 3);
3860 #endif  /* OPENSSL_NO_PSK */
3861     ADD_ALL_TESTS(test_custom_exts, 5);
3862     ADD_TEST(test_stateless);
3863     ADD_TEST(test_pha_key_update);
3864 #else
3865     ADD_ALL_TESTS(test_custom_exts, 3);
3866 #endif
3867     ADD_ALL_TESTS(test_serverinfo, 8);
3868     ADD_ALL_TESTS(test_export_key_mat, 4);
3869 #ifndef OPENSSL_NO_TLS1_3
3870     ADD_ALL_TESTS(test_export_key_mat_early, 3);
3871 #endif
3872     ADD_ALL_TESTS(test_ssl_clear, 2);
3873     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
3874     return 1;
3875 }
3876
3877 void cleanup_tests(void)
3878 {
3879     bio_s_mempacket_test_free();
3880 }