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