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