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