add basic references to the new methods in documentation
[openssl.git] / test / sslapitest.c
1 /*
2  * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <string.h>
11
12 #include <openssl/opensslconf.h>
13 #include <openssl/bio.h>
14 #include <openssl/crypto.h>
15 #include <openssl/ssl.h>
16 #include <openssl/ocsp.h>
17
18 #include "ssltestlib.h"
19 #include "testutil.h"
20 #include "e_os.h"
21 #include "../ssl/ssl_locl.h"
22
23 static char *cert = NULL;
24 static char *privkey = NULL;
25
26 #define LOG_BUFFER_SIZE 1024
27 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
28 static size_t server_log_buffer_index = 0;
29 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
30 static size_t client_log_buffer_index = 0;
31 static int error_writing_log = 0;
32
33 #ifndef OPENSSL_NO_OCSP
34 static const unsigned char orespder[] = "Dummy OCSP Response";
35 static int ocsp_server_called = 0;
36 static int ocsp_client_called = 0;
37
38 static int cdummyarg = 1;
39 static X509 *ocspcert = NULL;
40 #endif
41
42 #define NUM_EXTRA_CERTS 40
43
44 /*
45  * This structure is used to validate that the correct number of log messages
46  * of various types are emitted when emitting secret logs.
47  */
48 struct sslapitest_log_counts {
49     unsigned int rsa_key_exchange_count;
50     unsigned int master_secret_count;
51     unsigned int client_handshake_secret_count;
52     unsigned int server_handshake_secret_count;
53     unsigned int client_application_secret_count;
54     unsigned int server_application_secret_count;
55 };
56
57
58 static unsigned char serverinfov1[] = {
59     0xff, 0xff, /* Dummy extension type */
60     0x00, 0x01, /* Extension length is 1 byte */
61     0xff        /* Dummy extension data */
62 };
63
64 static unsigned char serverinfov2[] = {
65     0x00, 0x00, 0x00,
66     (unsigned char)(SSL_EXT_CLIENT_HELLO & 0xff), /* Dummy context - 4 bytes */
67     0xff, 0xff, /* Dummy extension type */
68     0x00, 0x01, /* Extension length is 1 byte */
69     0xff        /* Dummy extension data */
70 };
71
72 static void client_keylog_callback(const SSL *ssl, const char *line)
73 {
74     int line_length = strlen(line);
75
76     /* If the log doesn't fit, error out. */
77     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
78         TEST_info("Client log too full");
79         error_writing_log = 1;
80         return;
81     }
82
83     strcat(client_log_buffer, line);
84     client_log_buffer_index += line_length;
85     client_log_buffer[client_log_buffer_index++] = '\n';
86 }
87
88 static void server_keylog_callback(const SSL *ssl, const char *line)
89 {
90     int line_length = strlen(line);
91
92     /* If the log doesn't fit, error out. */
93     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
94         TEST_info("Server og too full");
95         error_writing_log = 1;
96         return;
97     }
98
99     strcat(server_log_buffer, line);
100     server_log_buffer_index += line_length;
101     server_log_buffer[server_log_buffer_index++] = '\n';
102 }
103
104 static int compare_hex_encoded_buffer(const char *hex_encoded,
105                                       size_t hex_length,
106                                       const uint8_t *raw,
107                                       size_t raw_length)
108 {
109     size_t i, j;
110     char hexed[3];
111
112     if (!TEST_size_t_eq(raw_length * 2, hex_length))
113         return 1;
114
115     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
116         sprintf(hexed, "%02x", raw[i]);
117         if (!TEST_int_eq(hexed[0], hex_encoded[j])
118                 || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
119             return 1;
120     }
121
122     return 0;
123 }
124
125 static int test_keylog_output(char *buffer, const SSL *ssl,
126                               const SSL_SESSION *session,
127                               struct sslapitest_log_counts *expected)
128 {
129     char *token = NULL;
130     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0};
131     size_t client_random_size = SSL3_RANDOM_SIZE;
132     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
133     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
134     unsigned int rsa_key_exchange_count = 0;
135     unsigned int master_secret_count = 0;
136     unsigned int client_handshake_secret_count = 0;
137     unsigned int server_handshake_secret_count = 0;
138     unsigned int client_application_secret_count = 0;
139     unsigned int server_application_secret_count = 0;
140
141     for (token = strtok(buffer, " \n"); token != NULL;
142          token = strtok(NULL, " \n")) {
143         if (strcmp(token, "RSA") == 0) {
144             /*
145              * Premaster secret. Tokens should be: 16 ASCII bytes of
146              * hex-encoded encrypted secret, then the hex-encoded pre-master
147              * secret.
148              */
149             if (!TEST_ptr(token = strtok(NULL, " \n")))
150                 return 0;
151             if (!TEST_size_t_eq(strlen(token), 16))
152                 return 0;
153             if (!TEST_ptr(token = strtok(NULL, " \n")))
154                 return 0;
155             /*
156              * We can't sensibly check the log because the premaster secret is
157              * transient, and OpenSSL doesn't keep hold of it once the master
158              * secret is generated.
159              */
160             rsa_key_exchange_count++;
161         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
162             /*
163              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
164              * client random, then the hex-encoded master secret.
165              */
166             client_random_size = SSL_get_client_random(ssl,
167                                                        actual_client_random,
168                                                        SSL3_RANDOM_SIZE);
169             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
170                 return 0;
171
172             if (!TEST_ptr(token = strtok(NULL, " \n")))
173                 return 0;
174             if (!TEST_size_t_eq(strlen(token), 64))
175                 return 0;
176             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
177                                                        actual_client_random,
178                                                        client_random_size)))
179                 return 0;
180
181             if (!TEST_ptr(token = strtok(NULL, " \n")))
182                 return 0;
183             master_key_size = SSL_SESSION_get_master_key(session,
184                                                          actual_master_key,
185                                                          master_key_size);
186             if (!TEST_size_t_ne(master_key_size, 0))
187                 return 0;
188             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
189                                                        actual_master_key,
190                                                        master_key_size)))
191                 return 0;
192             master_secret_count++;
193         } else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
194                     || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
195                     || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
196                     || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0) {
197             /*
198              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
199              * client random, and then the hex-encoded secret. In this case,
200              * we treat all of these secrets identically and then just
201              * distinguish between them when counting what we saw.
202              */
203             if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
204                 client_handshake_secret_count++;
205             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
206                 server_handshake_secret_count++;
207             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
208                 client_application_secret_count++;
209             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
210                 server_application_secret_count++;
211
212             client_random_size = SSL_get_client_random(ssl,
213                                                        actual_client_random,
214                                                        SSL3_RANDOM_SIZE);
215             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
216                 return 0;
217
218             if (!TEST_ptr(token = strtok(NULL, " \n")))
219                 return 0;
220             if (!TEST_size_t_eq(strlen(token), 64))
221                 return 0;
222             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
223                                                        actual_client_random,
224                                                        client_random_size)))
225                 return 0;
226
227             if (!TEST_ptr(token = strtok(NULL, " \n")))
228                 return 0;
229
230             /*
231              * TODO(TLS1.3): test that application traffic secrets are what
232              * we expect */
233         } else {
234             TEST_info("Unexpected token %s\n", token);
235             return 0;
236         }
237     }
238
239     /* Got what we expected? */
240     if (!TEST_size_t_eq(rsa_key_exchange_count,
241                         expected->rsa_key_exchange_count)
242             || !TEST_size_t_eq(master_secret_count,
243                                expected->master_secret_count)
244             || !TEST_size_t_eq(client_handshake_secret_count,
245                                expected->client_handshake_secret_count)
246             || !TEST_size_t_eq(server_handshake_secret_count,
247                                expected->server_handshake_secret_count)
248             || !TEST_size_t_eq(client_application_secret_count,
249                                expected->client_application_secret_count)
250             || !TEST_size_t_eq(server_application_secret_count,
251                                expected->server_application_secret_count))
252         return 0;
253     return 1;
254 }
255
256 static int test_keylog(void)
257 {
258     SSL_CTX *cctx = NULL, *sctx = NULL;
259     SSL *clientssl = NULL, *serverssl = NULL;
260     int testresult = 0;
261     struct sslapitest_log_counts expected = {0};
262
263     /* Clean up logging space */
264     memset(client_log_buffer, 0, sizeof(client_log_buffer));
265     memset(server_log_buffer, 0, sizeof(server_log_buffer));
266     client_log_buffer_index = 0;
267     server_log_buffer_index = 0;
268     error_writing_log = 0;
269
270     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
271                                        TLS_client_method(),
272                                        &sctx, &cctx, cert, privkey)))
273         return 0;
274
275     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
276     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
277     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
278
279     /* We also want to ensure that we use RSA-based key exchange. */
280     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
281         goto end;
282
283     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
284             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
285         goto end;
286     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
287     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
288                    == client_keylog_callback))
289         goto end;
290     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
291     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
292                    == server_keylog_callback))
293         goto end;
294
295     /* Now do a handshake and check that the logs have been written to. */
296     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
297                                       &clientssl, NULL, NULL))
298             || !TEST_true(create_ssl_connection(serverssl, clientssl,
299                                                 SSL_ERROR_NONE))
300             || !TEST_false(error_writing_log)
301             || !TEST_int_gt(client_log_buffer_index, 0)
302             || !TEST_int_gt(server_log_buffer_index, 0))
303         goto end;
304
305     /*
306      * Now we want to test that our output data was vaguely sensible. We
307      * do that by using strtok and confirming that we have more or less the
308      * data we expect. For both client and server, we expect to see one master
309      * secret. The client should also see a RSA key exchange.
310      */
311     expected.rsa_key_exchange_count = 1;
312     expected.master_secret_count = 1;
313     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
314                                       SSL_get_session(clientssl), &expected)))
315         goto end;
316
317     expected.rsa_key_exchange_count = 0;
318     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
319                                       SSL_get_session(serverssl), &expected)))
320         goto end;
321
322     testresult = 1;
323
324 end:
325     SSL_free(serverssl);
326     SSL_free(clientssl);
327     SSL_CTX_free(sctx);
328     SSL_CTX_free(cctx);
329
330     return testresult;
331 }
332
333 #ifndef OPENSSL_NO_TLS1_3
334 static int test_keylog_no_master_key(void)
335 {
336     SSL_CTX *cctx = NULL, *sctx = NULL;
337     SSL *clientssl = NULL, *serverssl = NULL;
338     int testresult = 0;
339     struct sslapitest_log_counts expected = {0};
340
341     /* Clean up logging space */
342     memset(client_log_buffer, 0, sizeof(client_log_buffer));
343     memset(server_log_buffer, 0, sizeof(server_log_buffer));
344     client_log_buffer_index = 0;
345     server_log_buffer_index = 0;
346     error_writing_log = 0;
347
348     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
349                              TLS_client_method(), &sctx,
350                              &cctx, cert, privkey)))
351         return 0;
352
353     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
354             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
355         goto end;
356
357     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
358     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
359                    == client_keylog_callback))
360         goto end;
361
362     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
363     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
364                    == server_keylog_callback))
365         goto end;
366
367     /* Now do a handshake and check that the logs have been written to. */
368     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
369                                       &clientssl, NULL, NULL))
370             || !TEST_true(create_ssl_connection(serverssl, clientssl,
371                                                 SSL_ERROR_NONE))
372             || !TEST_false(error_writing_log))
373         goto end;
374
375     /*
376      * Now we want to test that our output data was vaguely sensible. For this
377      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
378      * TLSv1.3, but we do expect both client and server to emit keys.
379      */
380     expected.client_handshake_secret_count = 1;
381     expected.server_handshake_secret_count = 1;
382     expected.client_application_secret_count = 1;
383     expected.server_application_secret_count = 1;
384     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
385                                       SSL_get_session(clientssl), &expected))
386             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
387                                              SSL_get_session(serverssl),
388                                              &expected)))
389         goto end;
390
391     testresult = 1;
392
393 end:
394     SSL_free(serverssl);
395     SSL_free(clientssl);
396     SSL_CTX_free(sctx);
397     SSL_CTX_free(cctx);
398
399     return testresult;
400 }
401 #endif
402
403 #ifndef OPENSSL_NO_TLS1_2
404 static int full_early_callback(SSL *s, int *al, void *arg)
405 {
406     int *ctr = arg;
407     const unsigned char *p;
408     int *exts;
409     /* We only configure two ciphers, but the SCSV is added automatically. */
410 #ifdef OPENSSL_NO_EC
411     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0x00, 0xff};
412 #else
413     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
414                                               0x2c, 0x00, 0xff};
415 #endif
416     const int expected_extensions[] = {
417 #ifndef OPENSSL_NO_EC
418                                        11, 10,
419 #endif
420                                        35, 13, 22, 23};
421     size_t len;
422
423     /* Make sure we can defer processing and get called back. */
424     if ((*ctr)++ == 0)
425         return -1;
426
427     len = SSL_early_get0_ciphers(s, &p);
428     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
429             || !TEST_size_t_eq(SSL_early_get0_compression_methods(s, &p), 1)
430             || !TEST_int_eq(*p, 0))
431         return 0;
432     if (!SSL_early_get1_extensions_present(s, &exts, &len))
433         return 0;
434     if (len != OSSL_NELEM(expected_extensions) ||
435         memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
436         printf("Early callback expected ClientHello extensions mismatch\n");
437         OPENSSL_free(exts);
438         return 0;
439     }
440     OPENSSL_free(exts);
441     return 1;
442 }
443
444 static int test_early_cb(void)
445 {
446     SSL_CTX *cctx = NULL, *sctx = NULL;
447     SSL *clientssl = NULL, *serverssl = NULL;
448     int testctr = 0, testresult = 0;
449
450     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
451                                        TLS_client_method(), &sctx,
452                                        &cctx, cert, privkey)))
453         goto end;
454     SSL_CTX_set_early_cb(sctx, full_early_callback, &testctr);
455
456     /* The gimpy cipher list we configure can't do TLS 1.3. */
457     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
458
459     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
460                         "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
461             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
462                                              &clientssl, NULL, NULL))
463             || !TEST_false(create_ssl_connection(serverssl, clientssl,
464                                                  SSL_ERROR_WANT_EARLY))
465                 /*
466                  * Passing a -1 literal is a hack since
467                  * the real value was lost.
468                  * */
469             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_EARLY)
470             || !TEST_true(create_ssl_connection(serverssl, clientssl,
471                                                 SSL_ERROR_NONE)))
472         goto end;
473
474     testresult = 1;
475
476 end:
477     SSL_free(serverssl);
478     SSL_free(clientssl);
479     SSL_CTX_free(sctx);
480     SSL_CTX_free(cctx);
481
482     return testresult;
483 }
484 #endif
485
486 static int execute_test_large_message(const SSL_METHOD *smeth,
487                                       const SSL_METHOD *cmeth, int read_ahead)
488 {
489     SSL_CTX *cctx = NULL, *sctx = NULL;
490     SSL *clientssl = NULL, *serverssl = NULL;
491     int testresult = 0;
492     int i;
493     BIO *certbio = NULL;
494     X509 *chaincert = NULL;
495     int certlen;
496
497     if (!TEST_ptr(certbio = BIO_new_file(cert, "r")))
498         goto end;
499     chaincert = PEM_read_bio_X509(certbio, NULL, NULL, NULL);
500     BIO_free(certbio);
501     certbio = NULL;
502     if (!TEST_ptr(chaincert))
503         goto end;
504
505     if (!TEST_true(create_ssl_ctx_pair(smeth, cmeth, &sctx,
506                                        &cctx, cert, privkey)))
507         goto end;
508
509     if (read_ahead) {
510         /*
511          * Test that read_ahead works correctly when dealing with large
512          * records
513          */
514         SSL_CTX_set_read_ahead(cctx, 1);
515     }
516
517     /*
518      * We assume the supplied certificate is big enough so that if we add
519      * NUM_EXTRA_CERTS it will make the overall message large enough. The
520      * default buffer size is requested to be 16k, but due to the way BUF_MEM
521      * works, it ends up allocating a little over 21k (16 * 4/3). So, in this
522      * test we need to have a message larger than that.
523      */
524     certlen = i2d_X509(chaincert, NULL);
525     OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
526                    (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
527     for (i = 0; i < NUM_EXTRA_CERTS; i++) {
528         if (!X509_up_ref(chaincert))
529             goto end;
530         if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
531             X509_free(chaincert);
532             goto end;
533         }
534     }
535
536     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
537                                       NULL, NULL))
538             || !TEST_true(create_ssl_connection(serverssl, clientssl,
539                                                 SSL_ERROR_NONE)))
540         goto end;
541
542     /*
543      * Calling SSL_clear() first is not required but this tests that SSL_clear()
544      * doesn't leak (when using enable-crypto-mdebug).
545      */
546     if (!TEST_true(SSL_clear(serverssl)))
547         goto end;
548
549     testresult = 1;
550  end:
551     X509_free(chaincert);
552     SSL_free(serverssl);
553     SSL_free(clientssl);
554     SSL_CTX_free(sctx);
555     SSL_CTX_free(cctx);
556
557     return testresult;
558 }
559
560 static int test_large_message_tls(void)
561 {
562     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
563                                       0);
564 }
565
566 static int test_large_message_tls_read_ahead(void)
567 {
568     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
569                                       1);
570 }
571
572 #ifndef OPENSSL_NO_DTLS
573 static int test_large_message_dtls(void)
574 {
575     /*
576      * read_ahead is not relevant to DTLS because DTLS always acts as if
577      * read_ahead is set.
578      */
579     return execute_test_large_message(DTLS_server_method(),
580                                       DTLS_client_method(), 0);
581 }
582 #endif
583
584 #ifndef OPENSSL_NO_OCSP
585 static int ocsp_server_cb(SSL *s, void *arg)
586 {
587     int *argi = (int *)arg;
588     unsigned char *copy = NULL;
589     STACK_OF(OCSP_RESPID) *ids = NULL;
590     OCSP_RESPID *id = NULL;
591
592     if (*argi == 2) {
593         /* In this test we are expecting exactly 1 OCSP_RESPID */
594         SSL_get_tlsext_status_ids(s, &ids);
595         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
596             return SSL_TLSEXT_ERR_ALERT_FATAL;
597
598         id = sk_OCSP_RESPID_value(ids, 0);
599         if (id == NULL || !OCSP_RESPID_match(id, ocspcert))
600             return SSL_TLSEXT_ERR_ALERT_FATAL;
601     } else if (*argi != 1) {
602         return SSL_TLSEXT_ERR_ALERT_FATAL;
603     }
604
605     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
606         return SSL_TLSEXT_ERR_ALERT_FATAL;
607
608     SSL_set_tlsext_status_ocsp_resp(s, copy, sizeof(orespder));
609     ocsp_server_called = 1;
610     return SSL_TLSEXT_ERR_OK;
611 }
612
613 static int ocsp_client_cb(SSL *s, void *arg)
614 {
615     int *argi = (int *)arg;
616     const unsigned char *respderin;
617     size_t len;
618
619     if (*argi != 1 && *argi != 2)
620         return 0;
621
622     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
623     if (!TEST_mem_eq(orespder, len, respderin, len))
624         return 0;
625
626     ocsp_client_called = 1;
627     return 1;
628 }
629
630 static int test_tlsext_status_type(void)
631 {
632     SSL_CTX *cctx = NULL, *sctx = NULL;
633     SSL *clientssl = NULL, *serverssl = NULL;
634     int testresult = 0;
635     STACK_OF(OCSP_RESPID) *ids = NULL;
636     OCSP_RESPID *id = NULL;
637     BIO *certbio = NULL;
638
639     if (!create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(), &sctx,
640                              &cctx, cert, privkey))
641         return 0;
642
643     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
644         goto end;
645
646     /* First just do various checks getting and setting tlsext_status_type */
647
648     clientssl = SSL_new(cctx);
649     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
650             || !TEST_true(SSL_set_tlsext_status_type(clientssl,
651                                                       TLSEXT_STATUSTYPE_ocsp))
652             || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
653                             TLSEXT_STATUSTYPE_ocsp))
654         goto end;
655
656     SSL_free(clientssl);
657     clientssl = NULL;
658
659     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
660      || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
661         goto end;
662
663     clientssl = SSL_new(cctx);
664     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
665         goto end;
666     SSL_free(clientssl);
667     clientssl = NULL;
668
669     /*
670      * Now actually do a handshake and check OCSP information is exchanged and
671      * the callbacks get called
672      */
673     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
674     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
675     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
676     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
677     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
678                                       &clientssl, NULL, NULL))
679             || !TEST_true(create_ssl_connection(serverssl, clientssl,
680                                                 SSL_ERROR_NONE))
681             || !TEST_true(ocsp_client_called)
682             || !TEST_true(ocsp_server_called))
683         goto end;
684     SSL_free(serverssl);
685     SSL_free(clientssl);
686     serverssl = NULL;
687     clientssl = NULL;
688
689     /* Try again but this time force the server side callback to fail */
690     ocsp_client_called = 0;
691     ocsp_server_called = 0;
692     cdummyarg = 0;
693     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
694                                       &clientssl, NULL, NULL))
695                 /* This should fail because the callback will fail */
696             || !TEST_false(create_ssl_connection(serverssl, clientssl,
697                                                  SSL_ERROR_NONE))
698             || !TEST_false(ocsp_client_called)
699             || !TEST_false(ocsp_server_called))
700         goto end;
701     SSL_free(serverssl);
702     SSL_free(clientssl);
703     serverssl = NULL;
704     clientssl = NULL;
705
706     /*
707      * This time we'll get the client to send an OCSP_RESPID that it will
708      * accept.
709      */
710     ocsp_client_called = 0;
711     ocsp_server_called = 0;
712     cdummyarg = 2;
713     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
714                                       &clientssl, NULL, NULL)))
715         goto end;
716
717     /*
718      * We'll just use any old cert for this test - it doesn't have to be an OCSP
719      * specific one. We'll use the server cert.
720      */
721     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
722             || !TEST_ptr(id = OCSP_RESPID_new())
723             || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
724             || !TEST_ptr(ocspcert = PEM_read_bio_X509(certbio,
725                                                       NULL, NULL, NULL))
726             || !TEST_true(OCSP_RESPID_set_by_key(id, ocspcert))
727             || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
728         goto end;
729     id = NULL;
730     SSL_set_tlsext_status_ids(clientssl, ids);
731     /* Control has been transferred */
732     ids = NULL;
733
734     BIO_free(certbio);
735     certbio = NULL;
736
737     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
738                                          SSL_ERROR_NONE))
739             || !TEST_true(ocsp_client_called)
740             || !TEST_true(ocsp_server_called))
741         goto end;
742
743     testresult = 1;
744
745  end:
746     SSL_free(serverssl);
747     SSL_free(clientssl);
748     SSL_CTX_free(sctx);
749     SSL_CTX_free(cctx);
750     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
751     OCSP_RESPID_free(id);
752     BIO_free(certbio);
753     X509_free(ocspcert);
754     ocspcert = NULL;
755
756     return testresult;
757 }
758 #endif
759
760 typedef struct ssl_session_test_fixture {
761     const char *test_case_name;
762     int use_ext_cache;
763     int use_int_cache;
764 } SSL_SESSION_TEST_FIXTURE;
765
766 static int new_called = 0, remove_called = 0;
767
768 static SSL_SESSION_TEST_FIXTURE
769 ssl_session_set_up(const char *const test_case_name)
770 {
771     SSL_SESSION_TEST_FIXTURE fixture;
772
773     fixture.test_case_name = test_case_name;
774     fixture.use_ext_cache = 1;
775     fixture.use_int_cache = 1;
776
777     new_called = remove_called = 0;
778
779     return fixture;
780 }
781
782 static void ssl_session_tear_down(SSL_SESSION_TEST_FIXTURE fixture)
783 {
784 }
785
786 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
787 {
788     new_called++;
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 int execute_test_session(SSL_SESSION_TEST_FIXTURE fix)
798 {
799     SSL_CTX *sctx = NULL, *cctx = NULL;
800     SSL *serverssl1 = NULL, *clientssl1 = NULL;
801     SSL *serverssl2 = NULL, *clientssl2 = NULL;
802 #ifndef OPENSSL_NO_TLS1_1
803     SSL *serverssl3 = NULL, *clientssl3 = NULL;
804 #endif
805     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
806     int testresult = 0;
807
808     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
809                                        TLS_client_method(), &sctx,
810                                        &cctx, cert, privkey)))
811         return 0;
812
813 #ifndef OPENSSL_NO_TLS1_2
814     /* Only allow TLS1.2 so we can force a connection failure later */
815     SSL_CTX_set_min_proto_version(cctx, TLS1_2_VERSION);
816 #endif
817
818     /* Set up session cache */
819     if (fix.use_ext_cache) {
820         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
821         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
822     }
823     if (fix.use_int_cache) {
824         /* Also covers instance where both are set */
825         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
826     } else {
827         SSL_CTX_set_session_cache_mode(cctx,
828                                        SSL_SESS_CACHE_CLIENT
829                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
830     }
831
832     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
833                                       NULL, NULL))
834             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
835                                                 SSL_ERROR_NONE))
836             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
837         goto end;
838
839     /* Should fail because it should already be in the cache */
840     if (fix.use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
841         goto end;
842     if (fix.use_ext_cache && (new_called != 1 || remove_called != 0))
843         goto end;
844
845     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
846                                       &clientssl2, NULL, NULL))
847             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
848                                                 SSL_ERROR_NONE)))
849         goto end;
850
851     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
852         goto end;
853
854     if (fix.use_ext_cache && (new_called != 2 || remove_called != 0))
855         goto end;
856
857     /*
858      * This should clear sess2 from the cache because it is a "bad" session.
859      * See SSL_set_session() documentation.
860      */
861     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
862         goto end;
863     if (fix.use_ext_cache && (new_called != 2 || remove_called != 1))
864         goto end;
865     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
866         goto end;
867
868     if (fix.use_int_cache) {
869         /* Should succeeded because it should not already be in the cache */
870         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
871                 || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
872             goto end;
873
874         /*
875          * This is for the purposes of internal cache testing...ignore the
876          * counter for external cache
877          */
878         if (fix.use_ext_cache)
879             remove_called--;
880     }
881
882     /* This shouldn't be in the cache so should fail */
883     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
884         goto end;
885
886     if (fix.use_ext_cache && (new_called != 2 || remove_called != 2))
887         goto end;
888
889 #if !defined(OPENSSL_NO_TLS1_1) && !defined(OPENSSL_NO_TLS1_2)
890     /* Force a connection failure */
891     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
892     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
893                                       &clientssl3, NULL, NULL))
894             || !TEST_true(SSL_set_session(clientssl3, sess1))
895         /* This should fail because of the mismatched protocol versions */
896             || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
897                                                  SSL_ERROR_NONE)))
898         goto end;
899
900     /* We should have automatically removed the session from the cache */
901     if (fix.use_ext_cache && (new_called != 2 || remove_called != 3))
902         goto end;
903
904     /* Should succeed because it should not already be in the cache */
905     if (fix.use_int_cache && !SSL_CTX_add_session(cctx, sess2))
906         goto end;
907 #endif
908
909     testresult = 1;
910
911  end:
912     SSL_free(serverssl1);
913     SSL_free(clientssl1);
914     SSL_free(serverssl2);
915     SSL_free(clientssl2);
916 #ifndef OPENSSL_NO_TLS1_1
917     SSL_free(serverssl3);
918     SSL_free(clientssl3);
919 #endif
920     SSL_SESSION_free(sess1);
921     SSL_SESSION_free(sess2);
922
923     /*
924      * Check if we need to remove any sessions up-refed for the external cache
925      */
926     if (new_called >= 1)
927         SSL_SESSION_free(sess1);
928     if (new_called >= 2)
929         SSL_SESSION_free(sess2);
930     SSL_CTX_free(sctx);
931     SSL_CTX_free(cctx);
932
933     return testresult;
934 }
935
936 static int test_session_with_only_int_cache(void)
937 {
938     SETUP_TEST_FIXTURE(SSL_SESSION_TEST_FIXTURE, ssl_session_set_up);
939     fixture.use_ext_cache = 0;
940     EXECUTE_TEST(execute_test_session, ssl_session_tear_down);
941 }
942
943 static int test_session_with_only_ext_cache(void)
944 {
945     SETUP_TEST_FIXTURE(SSL_SESSION_TEST_FIXTURE, ssl_session_set_up);
946     fixture.use_int_cache = 0;
947     EXECUTE_TEST(execute_test_session, ssl_session_tear_down);
948 }
949
950 static int test_session_with_both_cache(void)
951 {
952     SETUP_TEST_FIXTURE(SSL_SESSION_TEST_FIXTURE, ssl_session_set_up);
953     EXECUTE_TEST(execute_test_session, ssl_session_tear_down);
954 }
955
956 #define USE_NULL    0
957 #define USE_BIO_1   1
958 #define USE_BIO_2   2
959
960 #define TOTAL_SSL_SET_BIO_TESTS (3 * 3 * 3 * 3)
961
962 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
963 {
964     switch (type) {
965     case USE_NULL:
966         *res = NULL;
967         break;
968     case USE_BIO_1:
969         *res = bio1;
970         break;
971     case USE_BIO_2:
972         *res = bio2;
973         break;
974     }
975 }
976
977 static int test_ssl_set_bio(int idx)
978 {
979     SSL_CTX *ctx;
980     BIO *bio1 = NULL;
981     BIO *bio2 = NULL;
982     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
983     SSL *ssl = NULL;
984     int initrbio, initwbio, newrbio, newwbio;
985     int testresult = 0;
986
987     initrbio = idx % 3;
988     idx /= 3;
989     initwbio = idx % 3;
990     idx /= 3;
991     newrbio = idx % 3;
992     idx /= 3;
993     newwbio = idx;
994     if (!TEST_int_le(newwbio, 2))
995         return 0;
996
997     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
998                 || !TEST_ptr(ssl = SSL_new(ctx)))
999         goto end;
1000
1001     if (initrbio == USE_BIO_1
1002             || initwbio == USE_BIO_1
1003             || newrbio == USE_BIO_1
1004             || newwbio == USE_BIO_1) {
1005         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
1006             goto end;
1007     }
1008
1009     if (initrbio == USE_BIO_2
1010             || initwbio == USE_BIO_2
1011             || newrbio == USE_BIO_2
1012             || newwbio == USE_BIO_2) {
1013         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
1014             goto end;
1015     }
1016
1017     setupbio(&irbio, bio1, bio2, initrbio);
1018     setupbio(&iwbio, bio1, bio2, initwbio);
1019
1020     /*
1021      * We want to maintain our own refs to these BIO, so do an up ref for each
1022      * BIO that will have ownership transferred in the SSL_set_bio() call
1023      */
1024     if (irbio != NULL)
1025         BIO_up_ref(irbio);
1026     if (iwbio != NULL && iwbio != irbio)
1027         BIO_up_ref(iwbio);
1028
1029     SSL_set_bio(ssl, irbio, iwbio);
1030
1031     setupbio(&nrbio, bio1, bio2, newrbio);
1032     setupbio(&nwbio, bio1, bio2, newwbio);
1033
1034     /*
1035      * We will (maybe) transfer ownership again so do more up refs.
1036      * SSL_set_bio() has some really complicated ownership rules where BIOs have
1037      * already been set!
1038      */
1039     if (nrbio != NULL
1040             && nrbio != irbio
1041             && (nwbio != iwbio || nrbio != nwbio))
1042         BIO_up_ref(nrbio);
1043     if (nwbio != NULL
1044             && nwbio != nrbio
1045             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
1046         BIO_up_ref(nwbio);
1047
1048     SSL_set_bio(ssl, nrbio, nwbio);
1049
1050     testresult = 1;
1051
1052  end:
1053     SSL_free(ssl);
1054     BIO_free(bio1);
1055     BIO_free(bio2);
1056
1057     /*
1058      * This test is checking that the ref counting for SSL_set_bio is correct.
1059      * If we get here and we did too many frees then we will fail in the above
1060      * functions. If we haven't done enough then this will only be detected in
1061      * a crypto-mdebug build
1062      */
1063     SSL_CTX_free(ctx);
1064     return testresult;
1065 }
1066
1067 typedef struct ssl_bio_test_fixture {
1068     const char *test_case_name;
1069     int pop_ssl;
1070     enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } change_bio;
1071 } SSL_BIO_TEST_FIXTURE;
1072
1073 static SSL_BIO_TEST_FIXTURE ssl_bio_set_up(const char *const test_case_name)
1074 {
1075     SSL_BIO_TEST_FIXTURE fixture;
1076
1077     fixture.test_case_name = test_case_name;
1078     fixture.pop_ssl = 0;
1079     fixture.change_bio = NO_BIO_CHANGE;
1080     return fixture;
1081 }
1082
1083 static void ssl_bio_tear_down(SSL_BIO_TEST_FIXTURE fixture)
1084 {
1085 }
1086
1087 static int execute_test_ssl_bio(SSL_BIO_TEST_FIXTURE fix)
1088 {
1089     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
1090     SSL_CTX *ctx;
1091     SSL *ssl = NULL;
1092     int testresult = 0;
1093
1094     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
1095             || !TEST_ptr(ssl = SSL_new(ctx))
1096             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
1097             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
1098         goto end;
1099
1100     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
1101
1102     /*
1103      * If anything goes wrong here then we could leak memory, so this will
1104      * be caught in a crypto-mdebug build
1105      */
1106     BIO_push(sslbio, membio1);
1107
1108     /* Verify changing the rbio/wbio directly does not cause leaks */
1109     if (fix.change_bio != NO_BIO_CHANGE) {
1110         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem())))
1111             goto end;
1112         if (fix.change_bio == CHANGE_RBIO)
1113             SSL_set0_rbio(ssl, membio2);
1114         else
1115             SSL_set0_wbio(ssl, membio2);
1116     }
1117     ssl = NULL;
1118
1119     if (fix.pop_ssl)
1120         BIO_pop(sslbio);
1121     else
1122         BIO_pop(membio1);
1123
1124     testresult = 1;
1125  end:
1126     BIO_free(membio1);
1127     BIO_free(sslbio);
1128     SSL_free(ssl);
1129     SSL_CTX_free(ctx);
1130
1131     return testresult;
1132 }
1133
1134 static int test_ssl_bio_pop_next_bio(void)
1135 {
1136     SETUP_TEST_FIXTURE(SSL_BIO_TEST_FIXTURE, ssl_bio_set_up);
1137     EXECUTE_TEST(execute_test_ssl_bio, ssl_bio_tear_down);
1138 }
1139
1140 static int test_ssl_bio_pop_ssl_bio(void)
1141 {
1142     SETUP_TEST_FIXTURE(SSL_BIO_TEST_FIXTURE, ssl_bio_set_up);
1143     fixture.pop_ssl = 1;
1144     EXECUTE_TEST(execute_test_ssl_bio, ssl_bio_tear_down);
1145 }
1146
1147 static int test_ssl_bio_change_rbio(void)
1148 {
1149     SETUP_TEST_FIXTURE(SSL_BIO_TEST_FIXTURE, ssl_bio_set_up);
1150     fixture.change_bio = CHANGE_RBIO;
1151     EXECUTE_TEST(execute_test_ssl_bio, ssl_bio_tear_down);
1152 }
1153
1154 static int test_ssl_bio_change_wbio(void)
1155 {
1156     SETUP_TEST_FIXTURE(SSL_BIO_TEST_FIXTURE, ssl_bio_set_up);
1157     fixture.change_bio = CHANGE_WBIO;
1158     EXECUTE_TEST(execute_test_ssl_bio, ssl_bio_tear_down);
1159 }
1160
1161 typedef struct {
1162     /* The list of sig algs */
1163     const int *list;
1164     /* The length of the list */
1165     size_t listlen;
1166     /* A sigalgs list in string format */
1167     const char *liststr;
1168     /* Whether setting the list should succeed */
1169     int valid;
1170     /* Whether creating a connection with the list should succeed */
1171     int connsuccess;
1172 } sigalgs_list;
1173
1174 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
1175 #ifndef OPENSSL_NO_EC
1176 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
1177 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
1178 #endif
1179 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
1180 static const int invalidlist2[] = {NID_sha256, NID_undef};
1181 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
1182 static const int invalidlist4[] = {NID_sha256};
1183 static const sigalgs_list testsigalgs[] = {
1184     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
1185 #ifndef OPENSSL_NO_EC
1186     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
1187     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
1188 #endif
1189     {NULL, 0, "RSA+SHA256", 1, 1},
1190 #ifndef OPENSSL_NO_EC
1191     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
1192     {NULL, 0, "ECDSA+SHA512", 1, 0},
1193 #endif
1194     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
1195     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
1196     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
1197     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
1198     {NULL, 0, "RSA", 0, 0},
1199     {NULL, 0, "SHA256", 0, 0},
1200     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
1201     {NULL, 0, "Invalid", 0, 0}
1202 };
1203
1204 static int test_set_sigalgs(int idx)
1205 {
1206     SSL_CTX *cctx = NULL, *sctx = NULL;
1207     SSL *clientssl = NULL, *serverssl = NULL;
1208     int testresult = 0;
1209     const sigalgs_list *curr;
1210     int testctx;
1211
1212     /* Should never happen */
1213     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
1214         return 0;
1215
1216     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
1217     curr = testctx ? &testsigalgs[idx]
1218                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
1219
1220     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1221                                        TLS_client_method(), &sctx,
1222                                        &cctx, cert, privkey)))
1223         return 0;
1224
1225     /*
1226      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
1227      * for TLSv1.2 for now until we add a new API.
1228      */
1229     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1230
1231     if (testctx) {
1232         int ret;
1233
1234         if (curr->list != NULL)
1235             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
1236         else
1237             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
1238
1239         if (!ret) {
1240             if (curr->valid)
1241                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
1242             else
1243                 testresult = 1;
1244             goto end;
1245         }
1246         if (!curr->valid) {
1247             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
1248             goto end;
1249         }
1250     }
1251
1252     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1253                                       &clientssl, NULL, NULL)))
1254         goto end;
1255
1256     if (!testctx) {
1257         int ret;
1258
1259         if (curr->list != NULL)
1260             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
1261         else
1262             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
1263         if (!ret) {
1264             if (curr->valid)
1265                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
1266             else
1267                 testresult = 1;
1268             goto end;
1269         }
1270         if (!curr->valid)
1271             goto end;
1272     }
1273
1274     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
1275                                            SSL_ERROR_NONE),
1276                 curr->connsuccess))
1277         goto end;
1278
1279     testresult = 1;
1280
1281  end:
1282     SSL_free(serverssl);
1283     SSL_free(clientssl);
1284     SSL_CTX_free(sctx);
1285     SSL_CTX_free(cctx);
1286
1287     return testresult;
1288 }
1289
1290 #ifndef OPENSSL_NO_TLS1_3
1291
1292 #define MSG1    "Hello"
1293 #define MSG2    "World."
1294 #define MSG3    "This"
1295 #define MSG4    "is"
1296 #define MSG5    "a"
1297 #define MSG6    "test"
1298 #define MSG7    "message."
1299
1300 /*
1301  * Helper method to setup objects for early data test. Caller frees objects on
1302  * error.
1303  */
1304 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
1305                                 SSL **serverssl, SSL_SESSION **sess, int idx)
1306 {
1307     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1308                                        TLS_client_method(), sctx,
1309                                        cctx, cert, privkey)))
1310         return 0;
1311
1312     /* When idx == 1 we repeat the tests with read_ahead set */
1313     if (idx > 0) {
1314         SSL_CTX_set_read_ahead(*cctx, 1);
1315         SSL_CTX_set_read_ahead(*sctx, 1);
1316     }
1317
1318     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
1319                                       NULL, NULL))
1320             || !TEST_true(create_ssl_connection(*serverssl, *clientssl,
1321                                                 SSL_ERROR_NONE)))
1322         return 0;
1323
1324     *sess = SSL_get1_session(*clientssl);
1325     SSL_shutdown(*clientssl);
1326     SSL_shutdown(*serverssl);
1327     SSL_free(*serverssl);
1328     SSL_free(*clientssl);
1329     *serverssl = *clientssl = NULL;
1330
1331     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
1332                                       clientssl, NULL, NULL))
1333             || !TEST_true(SSL_set_session(*clientssl, *sess)))
1334         return 0;
1335
1336     return 1;
1337 }
1338
1339 static int test_early_data_read_write(int idx)
1340 {
1341     SSL_CTX *cctx = NULL, *sctx = NULL;
1342     SSL *clientssl = NULL, *serverssl = NULL;
1343     int testresult = 0;
1344     SSL_SESSION *sess = NULL;
1345     unsigned char buf[20], data[1024];
1346     size_t readbytes, written, eoedlen, rawread, rawwritten;
1347     BIO *rbio;
1348
1349     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1350                                         &serverssl, &sess, idx)))
1351         goto end;
1352
1353     /* Write and read some early data */
1354     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1355                                         &written))
1356             || !TEST_size_t_eq(written, strlen(MSG1))
1357             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
1358                                                 sizeof(buf), &readbytes),
1359                             SSL_READ_EARLY_DATA_SUCCESS)
1360             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
1361             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1362                             SSL_EARLY_DATA_ACCEPTED))
1363         goto end;
1364
1365     /*
1366      * Server should be able to write data, and client should be able to
1367      * read it.
1368      */
1369     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
1370                                         &written))
1371             || !TEST_size_t_eq(written, strlen(MSG2))
1372             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1373             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1374         goto end;
1375
1376     /* Even after reading normal data, client should be able write early data */
1377     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
1378                                         &written))
1379             || !TEST_size_t_eq(written, strlen(MSG3)))
1380         goto end;
1381
1382     /* Server should still be able read early data after writing data */
1383     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1384                                          &readbytes),
1385                      SSL_READ_EARLY_DATA_SUCCESS)
1386             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
1387         goto end;
1388
1389     /* Write more data from server and read it from client */
1390     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
1391                                         &written))
1392             || !TEST_size_t_eq(written, strlen(MSG4))
1393             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1394             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
1395         goto end;
1396
1397     /*
1398      * If client writes normal data it should mean writing early data is no
1399      * longer possible.
1400      */
1401     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
1402             || !TEST_size_t_eq(written, strlen(MSG5))
1403             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1404                             SSL_EARLY_DATA_ACCEPTED))
1405         goto end;
1406
1407     /*
1408      * At this point the client has written EndOfEarlyData, ClientFinished and
1409      * normal (fully protected) data. We are going to cause a delay between the
1410      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
1411      * in the read BIO, and then just put back the EndOfEarlyData message.
1412      */
1413     rbio = SSL_get_rbio(serverssl);
1414     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
1415             || !TEST_size_t_lt(rawread, sizeof(data))
1416             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
1417         goto end;
1418
1419     /* Record length is in the 4th and 5th bytes of the record header */
1420     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
1421     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
1422             || !TEST_size_t_eq(rawwritten, eoedlen))
1423         goto end;
1424
1425     /* Server should be told that there is no more early data */
1426     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1427                                          &readbytes),
1428                      SSL_READ_EARLY_DATA_FINISH)
1429             || !TEST_size_t_eq(readbytes, 0))
1430         goto end;
1431
1432     /*
1433      * Server has not finished init yet, so should still be able to write early
1434      * data.
1435      */
1436     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
1437                                         &written))
1438             || !TEST_size_t_eq(written, strlen(MSG6)))
1439         goto end;
1440
1441     /* Push the ClientFinished and the normal data back into the server rbio */
1442     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
1443                                 &rawwritten))
1444             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
1445         goto end;
1446
1447     /* Server should be able to read normal data */
1448     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1449             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
1450         goto end;
1451
1452     /* Client and server should not be able to write/read early data now */
1453     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
1454                                          &written)))
1455         goto end;
1456     ERR_clear_error();
1457     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1458                                          &readbytes),
1459                      SSL_READ_EARLY_DATA_ERROR))
1460         goto end;
1461     ERR_clear_error();
1462
1463     /* Client should be able to read the data sent by the server */
1464     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1465             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
1466         goto end;
1467
1468     /*
1469      * Make sure we process the NewSessionTicket. This arrives post-handshake.
1470      * We attempt a read which we do not expect to return any data.
1471      */
1472     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)))
1473         goto end;
1474
1475     /* Server should be able to write normal data */
1476     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
1477             || !TEST_size_t_eq(written, strlen(MSG7))
1478             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1479             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
1480         goto end;
1481
1482     SSL_SESSION_free(sess);
1483     sess = SSL_get1_session(clientssl);
1484
1485     SSL_shutdown(clientssl);
1486     SSL_shutdown(serverssl);
1487     SSL_free(serverssl);
1488     SSL_free(clientssl);
1489     serverssl = clientssl = NULL;
1490     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1491                                       &clientssl, NULL, NULL))
1492             || !TEST_true(SSL_set_session(clientssl, sess)))
1493         goto end;
1494
1495     /* Write and read some early data */
1496     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1497                                         &written))
1498             || !TEST_size_t_eq(written, strlen(MSG1))
1499             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1500                                                 &readbytes),
1501                             SSL_READ_EARLY_DATA_SUCCESS)
1502             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
1503         goto end;
1504
1505     if (!TEST_int_gt(SSL_connect(clientssl), 0)
1506             || !TEST_int_gt(SSL_accept(serverssl), 0))
1507         goto end;
1508
1509     /* Client and server should not be able to write/read early data now */
1510     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
1511                                          &written)))
1512         goto end;
1513     ERR_clear_error();
1514     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1515                                          &readbytes),
1516                      SSL_READ_EARLY_DATA_ERROR))
1517         goto end;
1518     ERR_clear_error();
1519
1520     /* Client and server should be able to write/read normal data */
1521     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
1522             || !TEST_size_t_eq(written, strlen(MSG5))
1523             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1524             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
1525         goto end;
1526
1527     testresult = 1;
1528
1529  end:
1530     SSL_SESSION_free(sess);
1531     SSL_free(serverssl);
1532     SSL_free(clientssl);
1533     SSL_CTX_free(sctx);
1534     SSL_CTX_free(cctx);
1535     return testresult;
1536 }
1537
1538 /*
1539  * Helper function to test that a server attempting to read early data can
1540  * handle a connection from a client where the early data should be skipped.
1541  */
1542 static int early_data_skip_helper(int hrr, int idx)
1543 {
1544     SSL_CTX *cctx = NULL, *sctx = NULL;
1545     SSL *clientssl = NULL, *serverssl = NULL;
1546     int testresult = 0;
1547     SSL_SESSION *sess = NULL;
1548     unsigned char buf[20];
1549     size_t readbytes, written;
1550
1551     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1552                                         &serverssl, &sess, idx)))
1553         goto end;
1554
1555     if (hrr) {
1556         /* Force an HRR to occur */
1557         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
1558             goto end;
1559     } else {
1560         /*
1561          * Deliberately corrupt the creation time. We take 20 seconds off the
1562          * time. It could be any value as long as it is not within tolerance.
1563          * This should mean the ticket is rejected.
1564          */
1565         if (!TEST_true(SSL_SESSION_set_time(sess, time(NULL) - 20)))
1566             goto end;
1567     }
1568
1569     /* Write some early data */
1570     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1571                                         &written))
1572             || !TEST_size_t_eq(written, strlen(MSG1)))
1573         goto end;
1574
1575     /* Server should reject the early data and skip over it */
1576     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1577                                          &readbytes),
1578                      SSL_READ_EARLY_DATA_FINISH)
1579             || !TEST_size_t_eq(readbytes, 0)
1580             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1581                             SSL_EARLY_DATA_REJECTED))
1582         goto end;
1583
1584     if (hrr) {
1585         /*
1586          * Finish off the handshake. We perform the same writes and reads as
1587          * further down but we expect them to fail due to the incomplete
1588          * handshake.
1589          */
1590         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
1591                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
1592                                &readbytes)))
1593             goto end;
1594     }
1595
1596     /* Should be able to send normal data despite rejection of early data */
1597     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
1598             || !TEST_size_t_eq(written, strlen(MSG2))
1599             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1600                             SSL_EARLY_DATA_REJECTED)
1601             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1602             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1603         goto end;
1604
1605     testresult = 1;
1606
1607  end:
1608     SSL_SESSION_free(sess);
1609     SSL_free(serverssl);
1610     SSL_free(clientssl);
1611     SSL_CTX_free(sctx);
1612     SSL_CTX_free(cctx);
1613     return testresult;
1614 }
1615
1616 /*
1617  * Test that a server attempting to read early data can handle a connection
1618  * from a client where the early data is not acceptable.
1619  */
1620 static int test_early_data_skip(int idx)
1621 {
1622     return early_data_skip_helper(0, idx);
1623 }
1624
1625 /*
1626  * Test that a server attempting to read early data can handle a connection
1627  * from a client where an HRR occurs.
1628  */
1629 static int test_early_data_skip_hrr(int idx)
1630 {
1631     return early_data_skip_helper(1, idx);
1632 }
1633
1634 /*
1635  * Test that a server attempting to read early data can handle a connection
1636  * from a client that doesn't send any.
1637  */
1638 static int test_early_data_not_sent(int idx)
1639 {
1640     SSL_CTX *cctx = NULL, *sctx = NULL;
1641     SSL *clientssl = NULL, *serverssl = NULL;
1642     int testresult = 0;
1643     SSL_SESSION *sess = NULL;
1644     unsigned char buf[20];
1645     size_t readbytes, written;
1646
1647     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1648                                         &serverssl, &sess, idx)))
1649         goto end;
1650
1651     /* Write some data - should block due to handshake with server */
1652     SSL_set_connect_state(clientssl);
1653     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
1654         goto end;
1655
1656     /* Server should detect that early data has not been sent */
1657     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1658                                          &readbytes),
1659                      SSL_READ_EARLY_DATA_FINISH)
1660             || !TEST_size_t_eq(readbytes, 0)
1661             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1662                             SSL_EARLY_DATA_NOT_SENT)
1663             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1664                             SSL_EARLY_DATA_NOT_SENT))
1665         goto end;
1666
1667     /* Continue writing the message we started earlier */
1668     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
1669             || !TEST_size_t_eq(written, strlen(MSG1))
1670             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1671             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
1672             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
1673             || !TEST_size_t_eq(written, strlen(MSG2)))
1674         goto end;
1675
1676     /*
1677      * Should block due to the NewSessionTicket arrival unless we're using
1678      * read_ahead
1679      */
1680     if (idx == 0) {
1681         if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)))
1682             goto end;
1683     }
1684
1685     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1686             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1687         goto end;
1688
1689     testresult = 1;
1690
1691  end:
1692     SSL_SESSION_free(sess);
1693     SSL_free(serverssl);
1694     SSL_free(clientssl);
1695     SSL_CTX_free(sctx);
1696     SSL_CTX_free(cctx);
1697     return testresult;
1698 }
1699
1700 /*
1701  * Test that a server that doesn't try to read early data can handle a
1702  * client sending some.
1703  */
1704 static int test_early_data_not_expected(int idx)
1705 {
1706     SSL_CTX *cctx = NULL, *sctx = NULL;
1707     SSL *clientssl = NULL, *serverssl = NULL;
1708     int testresult = 0;
1709     SSL_SESSION *sess = NULL;
1710     unsigned char buf[20];
1711     size_t readbytes, written;
1712
1713
1714     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1715                                         &serverssl, &sess, idx)))
1716         goto end;
1717
1718     /* Write some early data */
1719     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1720                                         &written)))
1721         goto end;
1722
1723     /*
1724      * Server should skip over early data and then block waiting for client to
1725      * continue handshake
1726      */
1727     if (!TEST_int_le(SSL_accept(serverssl), 0)
1728      || !TEST_int_gt(SSL_connect(clientssl), 0)
1729      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1730                      SSL_EARLY_DATA_REJECTED)
1731      || !TEST_int_gt(SSL_accept(serverssl), 0)
1732      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1733                      SSL_EARLY_DATA_REJECTED))
1734         goto end;
1735
1736     /* Send some normal data from client to server */
1737     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
1738             || !TEST_size_t_eq(written, strlen(MSG2)))
1739         goto end;
1740
1741     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1742             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1743         goto end;
1744
1745     testresult = 1;
1746
1747  end:
1748     SSL_SESSION_free(sess);
1749     SSL_free(serverssl);
1750     SSL_free(clientssl);
1751     SSL_CTX_free(sctx);
1752     SSL_CTX_free(cctx);
1753     return testresult;
1754 }
1755
1756
1757 # ifndef OPENSSL_NO_TLS1_2
1758 /*
1759  * Test that a server attempting to read early data can handle a connection
1760  * from a TLSv1.2 client.
1761  */
1762 static int test_early_data_tls1_2(int idx)
1763 {
1764     SSL_CTX *cctx = NULL, *sctx = NULL;
1765     SSL *clientssl = NULL, *serverssl = NULL;
1766     int testresult = 0;
1767     unsigned char buf[20];
1768     size_t readbytes, written;
1769
1770     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1771                                        TLS_client_method(), &sctx,
1772                                        &cctx, cert, privkey)))
1773         goto end;
1774
1775     /* When idx == 1 we repeat the tests with read_ahead set */
1776     if (idx > 0) {
1777         SSL_CTX_set_read_ahead(cctx, 1);
1778         SSL_CTX_set_read_ahead(sctx, 1);
1779     }
1780
1781     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1782                                       &clientssl, NULL, NULL)))
1783         goto end;
1784
1785     /* Write some data - should block due to handshake with server */
1786     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
1787     SSL_set_connect_state(clientssl);
1788     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
1789         goto end;
1790
1791     /*
1792      * Server should do TLSv1.2 handshake. First it will block waiting for more
1793      * messages from client after ServerDone. Then SSL_read_early_data should
1794      * finish and detect that early data has not been sent
1795      */
1796     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1797                                          &readbytes),
1798                      SSL_READ_EARLY_DATA_ERROR))
1799         goto end;
1800
1801     /*
1802      * Continue writing the message we started earlier. Will still block waiting
1803      * for the CCS/Finished from server
1804      */
1805     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
1806             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
1807                                                 &readbytes),
1808                             SSL_READ_EARLY_DATA_FINISH)
1809             || !TEST_size_t_eq(readbytes, 0)
1810             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1811                             SSL_EARLY_DATA_NOT_SENT))
1812         goto end;
1813
1814     /* Continue writing the message we started earlier */
1815     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
1816             || !TEST_size_t_eq(written, strlen(MSG1))
1817             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
1818                             SSL_EARLY_DATA_NOT_SENT)
1819             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
1820             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
1821             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
1822             || !TEST_size_t_eq(written, strlen(MSG2))
1823             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
1824             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1825         goto end;
1826
1827     testresult = 1;
1828
1829  end:
1830     SSL_free(serverssl);
1831     SSL_free(clientssl);
1832     SSL_CTX_free(sctx);
1833     SSL_CTX_free(cctx);
1834
1835     return testresult;
1836 }
1837 # endif /* OPENSSL_NO_TLS1_2 */
1838
1839 static int test_ciphersuite_change(void)
1840 {
1841     SSL_CTX *cctx = NULL, *sctx = NULL;
1842     SSL *clientssl = NULL, *serverssl = NULL;
1843     SSL_SESSION *clntsess = NULL;
1844     int testresult = 0;
1845     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
1846
1847     /* Create a session based on SHA-256 */
1848     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1849                                        TLS_client_method(), &sctx,
1850                                        &cctx, cert, privkey))
1851             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
1852                                                   "TLS13-AES-128-GCM-SHA256"))
1853             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1854                                           &clientssl, NULL, NULL))
1855             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1856                                                 SSL_ERROR_NONE)))
1857         goto end;
1858
1859     clntsess = SSL_get1_session(clientssl);
1860     /* Save for later */
1861     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
1862     SSL_shutdown(clientssl);
1863     SSL_shutdown(serverssl);
1864     SSL_free(serverssl);
1865     SSL_free(clientssl);
1866     serverssl = clientssl = NULL;
1867
1868     /* Check we can resume a session with a different SHA-256 ciphersuite */
1869     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
1870                                            "TLS13-CHACHA20-POLY1305-SHA256"))
1871             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1872                                              NULL, NULL))
1873             || !TEST_true(SSL_set_session(clientssl, clntsess))
1874             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1875                                                 SSL_ERROR_NONE))
1876             || !TEST_true(SSL_session_reused(clientssl)))
1877         goto end;
1878
1879     SSL_SESSION_free(clntsess);
1880     clntsess = SSL_get1_session(clientssl);
1881     SSL_shutdown(clientssl);
1882     SSL_shutdown(serverssl);
1883     SSL_free(serverssl);
1884     SSL_free(clientssl);
1885     serverssl = clientssl = NULL;
1886
1887     /*
1888      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
1889      * succeeds but does not resume.
1890      */
1891     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "TLS13-AES-256-GCM-SHA384"))
1892             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1893                                              NULL, NULL))
1894             || !TEST_true(SSL_set_session(clientssl, clntsess))
1895             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1896                                                 SSL_ERROR_SSL))
1897             || !TEST_false(SSL_session_reused(clientssl)))
1898         goto end;
1899
1900     SSL_SESSION_free(clntsess);
1901     clntsess = NULL;
1902     SSL_shutdown(clientssl);
1903     SSL_shutdown(serverssl);
1904     SSL_free(serverssl);
1905     SSL_free(clientssl);
1906     serverssl = clientssl = NULL;
1907
1908     /* Create a session based on SHA384 */
1909     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "TLS13-AES-256-GCM-SHA384"))
1910             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1911                                           &clientssl, NULL, NULL))
1912             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1913                                                 SSL_ERROR_NONE)))
1914         goto end;
1915
1916     clntsess = SSL_get1_session(clientssl);
1917     SSL_shutdown(clientssl);
1918     SSL_shutdown(serverssl);
1919     SSL_free(serverssl);
1920     SSL_free(clientssl);
1921     serverssl = clientssl = NULL;
1922
1923     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
1924                    "TLS13-AES-128-GCM-SHA256:TLS13-AES-256-GCM-SHA384"))
1925             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
1926                                                   "TLS13-AES-256-GCM-SHA384"))
1927             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1928                                              NULL, NULL))
1929             || !TEST_true(SSL_set_session(clientssl, clntsess))
1930                /*
1931                 * We use SSL_ERROR_WANT_READ below so that we can pause the
1932                 * connection after the initial ClientHello has been sent to
1933                 * enable us to make some session changes.
1934                 */
1935             || !TEST_false(create_ssl_connection(serverssl, clientssl,
1936                                                 SSL_ERROR_WANT_READ)))
1937         goto end;
1938
1939     /* Trick the client into thinking this session is for a different digest */
1940     clntsess->cipher = aes_128_gcm_sha256;
1941     clntsess->cipher_id = clntsess->cipher->id;
1942
1943     /*
1944      * Continue the previously started connection. Server has selected a SHA-384
1945      * ciphersuite, but client thinks the session is for SHA-256, so it should
1946      * bail out.
1947      */
1948     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
1949                                                 SSL_ERROR_SSL))
1950             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
1951                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
1952         goto end;
1953
1954     testresult = 1;
1955
1956  end:
1957     SSL_SESSION_free(clntsess);
1958     SSL_free(serverssl);
1959     SSL_free(clientssl);
1960     SSL_CTX_free(sctx);
1961     SSL_CTX_free(cctx);
1962
1963     return testresult;
1964 }
1965
1966
1967 static SSL_SESSION *psk = NULL;
1968 static const char *pskid = "Identity";
1969 static const char *srvid;
1970
1971 static int use_session_cb_cnt = 0;
1972 static int find_session_cb_cnt = 0;
1973
1974 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
1975                           size_t *idlen, SSL_SESSION **sess)
1976 {
1977     switch (++use_session_cb_cnt) {
1978     case 1:
1979         /* The first call should always have a NULL md */
1980         if (md != NULL)
1981             return 0;
1982         break;
1983
1984     case 2:
1985         /* The second call should always have an md */
1986         if (md == NULL)
1987             return 0;
1988         break;
1989
1990     default:
1991         /* We should only be called a maximum of twice */
1992         return 0;
1993     }
1994
1995     if (psk != NULL)
1996         SSL_SESSION_up_ref(psk);
1997
1998     *sess = psk;
1999     *id = (const unsigned char *)pskid;
2000     *idlen = strlen(pskid);
2001
2002     return 1;
2003 }
2004
2005 static int find_session_cb(SSL *ssl, const unsigned char *identity,
2006                            size_t identity_len, SSL_SESSION **sess)
2007 {
2008     find_session_cb_cnt++;
2009
2010     /* We should only ever be called a maximum of twice per connection */
2011     if (find_session_cb_cnt > 2)
2012         return 0;
2013
2014     if (psk == NULL)
2015         return 0;
2016
2017     /* Identity should match that set by the client */
2018     if (strlen(srvid) != identity_len
2019             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
2020         /* No PSK found, continue but without a PSK */
2021         *sess = NULL;
2022         return 1;
2023     }
2024
2025     SSL_SESSION_up_ref(psk);
2026     *sess = psk;
2027
2028     return 1;
2029 }
2030
2031 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
2032
2033 static int test_tls13_psk(void)
2034 {
2035     SSL_CTX *sctx = NULL, *cctx = NULL;
2036     SSL *serverssl = NULL, *clientssl = NULL;
2037     const SSL_CIPHER *cipher = NULL;
2038     const unsigned char key[] = {
2039         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
2040         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
2041         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
2042         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
2043     };
2044     int testresult = 0;
2045
2046     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2047                                        TLS_client_method(), &sctx,
2048                                        &cctx, cert, privkey)))
2049         goto end;
2050
2051     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2052     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2053     srvid = pskid;
2054
2055     /* Check we can create a connection if callback decides not to send a PSK */
2056     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2057                                              NULL, NULL))
2058             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2059                                                 SSL_ERROR_NONE))
2060             || !TEST_false(SSL_session_reused(clientssl))
2061             || !TEST_false(SSL_session_reused(serverssl))
2062             || !TEST_true(use_session_cb_cnt == 1)
2063             || !TEST_true(find_session_cb_cnt == 0))
2064         goto end;
2065
2066     shutdown_ssl_connection(serverssl, clientssl);
2067     serverssl = clientssl = NULL;
2068     use_session_cb_cnt = 0;
2069
2070     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2071                                              NULL, NULL)))
2072         goto end;
2073
2074     /* Create the PSK */
2075     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_256_GCM_SHA384_BYTES);
2076     psk = SSL_SESSION_new();
2077     if (!TEST_ptr(psk)
2078             || !TEST_ptr(cipher)
2079             || !TEST_true(SSL_SESSION_set1_master_key(psk, key, sizeof(key)))
2080             || !TEST_true(SSL_SESSION_set_cipher(psk, cipher))
2081             || !TEST_true(SSL_SESSION_set_protocol_version(psk,
2082                                                            TLS1_3_VERSION)))
2083         goto end;
2084
2085     /* Check we can create a connection and the PSK is used */
2086     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2087             || !TEST_true(SSL_session_reused(clientssl))
2088             || !TEST_true(SSL_session_reused(serverssl))
2089             || !TEST_true(use_session_cb_cnt == 1)
2090             || !TEST_true(find_session_cb_cnt == 1))
2091         goto end;
2092
2093     shutdown_ssl_connection(serverssl, clientssl);
2094     serverssl = clientssl = NULL;
2095     use_session_cb_cnt = find_session_cb_cnt = 0;
2096
2097     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2098                                              NULL, NULL)))
2099         goto end;
2100
2101     /* Force an HRR */
2102     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2103         goto end;
2104
2105     /*
2106      * Check we can create a connection, the PSK is used and the callbacks are
2107      * called twice.
2108      */
2109     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2110             || !TEST_true(SSL_session_reused(clientssl))
2111             || !TEST_true(SSL_session_reused(serverssl))
2112             || !TEST_true(use_session_cb_cnt == 2)
2113             || !TEST_true(find_session_cb_cnt == 2))
2114         goto end;
2115
2116     shutdown_ssl_connection(serverssl, clientssl);
2117     serverssl = clientssl = NULL;
2118     use_session_cb_cnt = find_session_cb_cnt = 0;
2119
2120     /*
2121      * Check that if the server rejects the PSK we can still connect, but with
2122      * a full handshake
2123      */
2124     srvid = "Dummy Identity";
2125     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2126                                              NULL, NULL))
2127             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2128                                                 SSL_ERROR_NONE))
2129             || !TEST_false(SSL_session_reused(clientssl))
2130             || !TEST_false(SSL_session_reused(serverssl))
2131             || !TEST_true(use_session_cb_cnt == 1)
2132             || !TEST_true(find_session_cb_cnt == 1))
2133         goto end;
2134
2135     shutdown_ssl_connection(serverssl, clientssl);
2136     serverssl = clientssl = NULL;
2137     testresult = 1;
2138
2139  end:
2140     SSL_SESSION_free(psk);
2141     SSL_free(serverssl);
2142     SSL_free(clientssl);
2143     SSL_CTX_free(sctx);
2144     SSL_CTX_free(cctx);
2145     return testresult;
2146 }
2147
2148 #endif /* OPENSSL_NO_TLS1_3 */
2149
2150 static int clntaddoldcb = 0;
2151 static int clntparseoldcb = 0;
2152 static int srvaddoldcb = 0;
2153 static int srvparseoldcb = 0;
2154 static int clntaddnewcb = 0;
2155 static int clntparsenewcb = 0;
2156 static int srvaddnewcb = 0;
2157 static int srvparsenewcb = 0;
2158 static int snicb = 0;
2159
2160 #define TEST_EXT_TYPE1  0xff00
2161
2162 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
2163                       size_t *outlen, int *al, void *add_arg)
2164 {
2165     int *server = (int *)add_arg;
2166     unsigned char *data;
2167
2168     if (SSL_is_server(s))
2169         srvaddoldcb++;
2170     else
2171         clntaddoldcb++;
2172
2173     if (*server != SSL_is_server(s)
2174             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
2175         return -1;
2176
2177     *data = 1;
2178     *out = data;
2179     *outlen = sizeof(char);
2180     return 1;
2181 }
2182
2183 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
2184                         void *add_arg)
2185 {
2186     OPENSSL_free((unsigned char *)out);
2187 }
2188
2189 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
2190                         size_t inlen, int *al, void *parse_arg)
2191 {
2192     int *server = (int *)parse_arg;
2193
2194     if (SSL_is_server(s))
2195         srvparseoldcb++;
2196     else
2197         clntparseoldcb++;
2198
2199     if (*server != SSL_is_server(s)
2200             || inlen != sizeof(char)
2201             || *in != 1)
2202         return -1;
2203
2204     return 1;
2205 }
2206
2207 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
2208                       const unsigned char **out, size_t *outlen, X509 *x,
2209                       size_t chainidx, int *al, void *add_arg)
2210 {
2211     int *server = (int *)add_arg;
2212     unsigned char *data;
2213
2214     if (SSL_is_server(s))
2215         srvaddnewcb++;
2216     else
2217         clntaddnewcb++;
2218
2219     if (*server != SSL_is_server(s)
2220             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
2221         return -1;
2222
2223     *data = 1;
2224     *out = data;
2225     *outlen = sizeof(*data);
2226     return 1;
2227 }
2228
2229 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
2230                         const unsigned char *out, void *add_arg)
2231 {
2232     OPENSSL_free((unsigned char *)out);
2233 }
2234
2235 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
2236                         const unsigned char *in, size_t inlen, X509 *x,
2237                         size_t chainidx, int *al, void *parse_arg)
2238 {
2239     int *server = (int *)parse_arg;
2240
2241     if (SSL_is_server(s))
2242         srvparsenewcb++;
2243     else
2244         clntparsenewcb++;
2245
2246     if (*server != SSL_is_server(s)
2247             || inlen != sizeof(char) || *in != 1)
2248         return -1;
2249
2250     return 1;
2251 }
2252
2253 static int sni_cb(SSL *s, int *al, void *arg)
2254 {
2255     SSL_CTX *ctx = (SSL_CTX *)arg;
2256
2257     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
2258         *al = SSL_AD_INTERNAL_ERROR;
2259         return SSL_TLSEXT_ERR_ALERT_FATAL;
2260     }
2261     snicb++;
2262     return SSL_TLSEXT_ERR_OK;
2263 }
2264
2265 /*
2266  * Custom call back tests.
2267  * Test 0: Old style callbacks in TLSv1.2
2268  * Test 1: New style callbacks in TLSv1.2
2269  * Test 2: New style callbacks in TLSv1.2 with SNI
2270  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
2271  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
2272  */
2273 static int test_custom_exts(int tst)
2274 {
2275     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
2276     SSL *clientssl = NULL, *serverssl = NULL;
2277     int testresult = 0;
2278     static int server = 1;
2279     static int client = 0;
2280     SSL_SESSION *sess = NULL;
2281     unsigned int context;
2282
2283     /* Reset callback counters */
2284     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
2285     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
2286     snicb = 0;
2287
2288     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2289                                        TLS_client_method(), &sctx,
2290                                        &cctx, cert, privkey)))
2291         goto end;
2292
2293     if (tst == 2
2294             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL, &sctx2,
2295                                               NULL, cert, privkey)))
2296         goto end;
2297
2298
2299     if (tst < 3) {
2300         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
2301         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
2302         if (sctx2 != NULL)
2303             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
2304     }
2305
2306     if (tst == 4) {
2307         context = SSL_EXT_CLIENT_HELLO
2308                   | SSL_EXT_TLS1_2_SERVER_HELLO
2309                   | SSL_EXT_TLS1_3_SERVER_HELLO
2310                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
2311                   | SSL_EXT_TLS1_3_CERTIFICATE
2312                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
2313     } else {
2314         context = SSL_EXT_CLIENT_HELLO
2315                   | SSL_EXT_TLS1_2_SERVER_HELLO
2316                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
2317     }
2318
2319     /* Create a client side custom extension */
2320     if (tst == 0) {
2321         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
2322                                                      old_add_cb, old_free_cb,
2323                                                      &client, old_parse_cb,
2324                                                      &client)))
2325             goto end;
2326     } else {
2327         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
2328                                               new_add_cb, new_free_cb,
2329                                               &client, new_parse_cb, &client)))
2330             goto end;
2331     }
2332
2333     /* Should not be able to add duplicates */
2334     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
2335                                                   old_add_cb, old_free_cb,
2336                                                   &client, old_parse_cb,
2337                                                   &client))
2338             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
2339                                                   context, new_add_cb,
2340                                                   new_free_cb, &client,
2341                                                   new_parse_cb, &client)))
2342         goto end;
2343
2344     /* Create a server side custom extension */
2345     if (tst == 0) {
2346         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
2347                                                      old_add_cb, old_free_cb,
2348                                                      &server, old_parse_cb,
2349                                                      &server)))
2350             goto end;
2351     } else {
2352         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
2353                                               new_add_cb, new_free_cb,
2354                                               &server, new_parse_cb, &server)))
2355             goto end;
2356         if (sctx2 != NULL
2357                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
2358                                                      context, new_add_cb,
2359                                                      new_free_cb, &server,
2360                                                      new_parse_cb, &server)))
2361             goto end;
2362     }
2363
2364     /* Should not be able to add duplicates */
2365     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
2366                                                   old_add_cb, old_free_cb,
2367                                                   &server, old_parse_cb,
2368                                                   &server))
2369             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
2370                                                   context, new_add_cb,
2371                                                   new_free_cb, &server,
2372                                                   new_parse_cb, &server)))
2373         goto end;
2374
2375     if (tst == 2) {
2376         /* Set up SNI */
2377         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
2378                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
2379             goto end;
2380     }
2381
2382     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2383                                       &clientssl, NULL, NULL))
2384             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2385                                                 SSL_ERROR_NONE)))
2386         goto end;
2387
2388     if (tst == 0) {
2389         if (clntaddoldcb != 1
2390                 || clntparseoldcb != 1
2391                 || srvaddoldcb != 1
2392                 || srvparseoldcb != 1)
2393             goto end;
2394     } else if (tst == 1 || tst == 2 || tst == 3) {
2395         if (clntaddnewcb != 1
2396                 || clntparsenewcb != 1
2397                 || srvaddnewcb != 1
2398                 || srvparsenewcb != 1
2399                 || (tst != 2 && snicb != 0)
2400                 || (tst == 2 && snicb != 1))
2401             goto end;
2402     } else {
2403         if (clntaddnewcb != 1
2404                 || clntparsenewcb != 4
2405                 || srvaddnewcb != 4
2406                 || srvparsenewcb != 1)
2407             goto end;
2408     }
2409
2410     sess = SSL_get1_session(clientssl);
2411     SSL_shutdown(clientssl);
2412     SSL_shutdown(serverssl);
2413     SSL_free(serverssl);
2414     SSL_free(clientssl);
2415     serverssl = clientssl = NULL;
2416
2417     if (tst == 3) {
2418         /* We don't bother with the resumption aspects for this test */
2419         testresult = 1;
2420         goto end;
2421     }
2422
2423     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2424                                       NULL, NULL))
2425             || !TEST_true(SSL_set_session(clientssl, sess))
2426             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2427                                                SSL_ERROR_NONE)))
2428         goto end;
2429
2430     /*
2431      * For a resumed session we expect to add the ClientHello extension. For the
2432      * old style callbacks we ignore it on the server side because they set
2433      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
2434      * them.
2435      */
2436     if (tst == 0) {
2437         if (clntaddoldcb != 2
2438                 || clntparseoldcb != 1
2439                 || srvaddoldcb != 1
2440                 || srvparseoldcb != 1)
2441             goto end;
2442     } else if (tst == 1 || tst == 2 || tst == 3) {
2443         if (clntaddnewcb != 2
2444                 || clntparsenewcb != 2
2445                 || srvaddnewcb != 2
2446                 || srvparsenewcb != 2)
2447             goto end;
2448     } else {
2449         /* No Certificate message extensions in the resumption handshake */
2450         if (clntaddnewcb != 2
2451                 || clntparsenewcb != 7
2452                 || srvaddnewcb != 7
2453                 || srvparsenewcb != 2)
2454             goto end;
2455     }
2456
2457     testresult = 1;
2458
2459 end:
2460     SSL_SESSION_free(sess);
2461     SSL_free(serverssl);
2462     SSL_free(clientssl);
2463     SSL_CTX_free(sctx2);
2464     SSL_CTX_free(sctx);
2465     SSL_CTX_free(cctx);
2466     return testresult;
2467 }
2468
2469 /*
2470  * Test loading of serverinfo data in various formats. test_sslmessages actually
2471  * tests to make sure the extensions appear in the handshake
2472  */
2473 static int test_serverinfo(int tst)
2474 {
2475     unsigned int version;
2476     unsigned char *sibuf;
2477     size_t sibuflen;
2478     int ret, expected, testresult = 0;
2479     SSL_CTX *ctx;
2480
2481     ctx = SSL_CTX_new(TLS_method());
2482     if (!TEST_ptr(ctx))
2483         goto end;
2484
2485     if ((tst & 0x01) == 0x01)
2486         version = SSL_SERVERINFOV2;
2487     else
2488         version = SSL_SERVERINFOV1;
2489
2490     if ((tst & 0x02) == 0x02) {
2491         sibuf = serverinfov2;
2492         sibuflen = sizeof(serverinfov2);
2493         expected = (version == SSL_SERVERINFOV2);
2494     } else {
2495         sibuf = serverinfov1;
2496         sibuflen = sizeof(serverinfov1);
2497         expected = (version == SSL_SERVERINFOV1);
2498     }
2499
2500     if ((tst & 0x04) == 0x04) {
2501         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
2502     } else {
2503         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
2504
2505         /*
2506          * The version variable is irrelevant in this case - it's what is in the
2507          * buffer that matters
2508          */
2509         if ((tst & 0x02) == 0x02)
2510             expected = 0;
2511         else
2512             expected = 1;
2513     }
2514
2515     if (!TEST_true(ret == expected))
2516         goto end;
2517
2518     testresult = 1;
2519
2520  end:
2521     SSL_CTX_free(ctx);
2522
2523     return testresult;
2524 }
2525
2526 /*
2527  * Test that SSL_export_keying_material() produces expected results. There are
2528  * no test vectors so all we do is test that both sides of the communication
2529  * produce the same results for different protocol versions.
2530  */
2531 static int test_export_key_mat(int tst)
2532 {
2533     int testresult = 0;
2534     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
2535     SSL *clientssl = NULL, *serverssl = NULL;
2536     const char label[] = "test label";
2537     const unsigned char context[] = "context";
2538     const unsigned char *emptycontext = NULL;
2539     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
2540     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
2541     const int protocols[] = {
2542         TLS1_VERSION,
2543         TLS1_1_VERSION,
2544         TLS1_2_VERSION,
2545         TLS1_3_VERSION
2546     };
2547
2548 #ifdef OPENSSL_NO_TLS1
2549     if (tst == 0)
2550         return 1;
2551 #endif
2552 #ifdef OPENSSL_NO_TLS1_1
2553     if (tst == 1)
2554         return 1;
2555 #endif
2556 #ifdef OPENSSL_NO_TLS1_2
2557     if (tst == 2)
2558         return 1;
2559 #endif
2560 #ifdef OPENSSL_NO_TLS1_3
2561     if (tst == 3)
2562         return 1;
2563 #endif
2564     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2565                                        TLS_client_method(), &sctx,
2566                                        &cctx, cert, privkey)))
2567         goto end;
2568
2569     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
2570     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
2571     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
2572
2573     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
2574                                       NULL))
2575             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2576                                                 SSL_ERROR_NONE)))
2577         goto end;
2578
2579     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
2580                                                 sizeof(ckeymat1), label,
2581                                                 sizeof(label) - 1, context,
2582                                                 sizeof(context) - 1, 1), 1)
2583             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
2584                                                        sizeof(ckeymat2), label,
2585                                                        sizeof(label) - 1,
2586                                                        emptycontext,
2587                                                        0, 1), 1)
2588             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
2589                                                        sizeof(ckeymat3), label,
2590                                                        sizeof(label) - 1,
2591                                                        NULL, 0, 0), 1)
2592             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
2593                                                        sizeof(skeymat1), label,
2594                                                        sizeof(label) - 1,
2595                                                        context,
2596                                                        sizeof(context) -1, 1),
2597                             1)
2598             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
2599                                                        sizeof(skeymat2), label,
2600                                                        sizeof(label) - 1,
2601                                                        emptycontext,
2602                                                        0, 1), 1)
2603             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
2604                                                        sizeof(skeymat3), label,
2605                                                        sizeof(label) - 1,
2606                                                        NULL, 0, 0), 1)
2607                /*
2608                 * Check that both sides created the same key material with the
2609                 * same context.
2610                 */
2611             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
2612                             sizeof(skeymat1))
2613                /*
2614                 * Check that both sides created the same key material with an
2615                 * empty context.
2616                 */
2617             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
2618                             sizeof(skeymat2))
2619                /*
2620                 * Check that both sides created the same key material without a
2621                 * context.
2622                 */
2623             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
2624                             sizeof(skeymat3))
2625                /* Different contexts should produce different results */
2626             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
2627                             sizeof(ckeymat2)))
2628         goto end;
2629
2630     /*
2631      * Check that an empty context and no context produce different results in
2632      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
2633      */
2634     if ((tst != 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
2635                                   sizeof(ckeymat3)))
2636             || (tst ==3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
2637                                         sizeof(ckeymat3))))
2638         goto end;
2639
2640     testresult = 1;
2641
2642  end:
2643     SSL_free(serverssl);
2644     SSL_free(clientssl);
2645     SSL_CTX_free(sctx2);
2646     SSL_CTX_free(sctx);
2647     SSL_CTX_free(cctx);
2648
2649     return testresult;
2650 }
2651
2652 static int test_ssl_clear(int idx)
2653 {
2654     SSL_CTX *cctx = NULL, *sctx = NULL;
2655     SSL *clientssl = NULL, *serverssl = NULL;
2656     int testresult = 0;
2657
2658 #ifdef OPENSSL_NO_TLS1_2
2659     if (idx == 1)
2660         return 1;
2661 #endif
2662
2663     /* Create an initial connection */
2664     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
2665                                        TLS_client_method(), &sctx,
2666                                        &cctx, cert, privkey))
2667             || (idx == 1
2668                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
2669                                                             TLS1_2_VERSION)))
2670             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2671                                           &clientssl, NULL, NULL))
2672             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2673                                                 SSL_ERROR_NONE)))
2674         goto end;
2675
2676     SSL_shutdown(clientssl);
2677     SSL_shutdown(serverssl);
2678     SSL_free(serverssl);
2679     serverssl = NULL;
2680
2681     /* Clear clientssl - we're going to reuse the object */
2682     if (!TEST_true(SSL_clear(clientssl)))
2683         goto end;
2684
2685     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2686                                              NULL, NULL))
2687             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2688                                                 SSL_ERROR_NONE))
2689             || !TEST_true(SSL_session_reused(clientssl)))
2690         goto end;
2691
2692     SSL_shutdown(clientssl);
2693     SSL_shutdown(serverssl);
2694
2695     testresult = 1;
2696
2697  end:
2698     SSL_free(serverssl);
2699     SSL_free(clientssl);
2700     SSL_CTX_free(sctx);
2701     SSL_CTX_free(cctx);
2702
2703     return testresult;
2704 }
2705
2706 int test_main(int argc, char *argv[])
2707 {
2708     int testresult = 1;
2709
2710     if (argc != 3) {
2711         TEST_error("Wrong argument count");
2712         return 0;
2713     }
2714
2715     cert = argv[1];
2716     privkey = argv[2];
2717
2718     ADD_TEST(test_large_message_tls);
2719     ADD_TEST(test_large_message_tls_read_ahead);
2720 #ifndef OPENSSL_NO_DTLS
2721     ADD_TEST(test_large_message_dtls);
2722 #endif
2723 #ifndef OPENSSL_NO_OCSP
2724     ADD_TEST(test_tlsext_status_type);
2725 #endif
2726     ADD_TEST(test_session_with_only_int_cache);
2727     ADD_TEST(test_session_with_only_ext_cache);
2728     ADD_TEST(test_session_with_both_cache);
2729     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
2730     ADD_TEST(test_ssl_bio_pop_next_bio);
2731     ADD_TEST(test_ssl_bio_pop_ssl_bio);
2732     ADD_TEST(test_ssl_bio_change_rbio);
2733     ADD_TEST(test_ssl_bio_change_wbio);
2734     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
2735     ADD_TEST(test_keylog);
2736 #ifndef OPENSSL_NO_TLS1_3
2737     ADD_TEST(test_keylog_no_master_key);
2738 #endif
2739 #ifndef OPENSSL_NO_TLS1_2
2740     ADD_TEST(test_early_cb);
2741 #endif
2742 #ifndef OPENSSL_NO_TLS1_3
2743     ADD_ALL_TESTS(test_early_data_read_write, 2);
2744     ADD_ALL_TESTS(test_early_data_skip, 2);
2745     ADD_ALL_TESTS(test_early_data_skip_hrr, 2);
2746     ADD_ALL_TESTS(test_early_data_not_sent, 2);
2747     ADD_ALL_TESTS(test_early_data_not_expected, 2);
2748 # ifndef OPENSSL_NO_TLS1_2
2749     ADD_ALL_TESTS(test_early_data_tls1_2, 2);
2750 # endif
2751 #endif
2752 #ifndef OPENSSL_NO_TLS1_3
2753     ADD_TEST(test_ciphersuite_change);
2754     ADD_TEST(test_tls13_psk);
2755     ADD_ALL_TESTS(test_custom_exts, 5);
2756 #else
2757     ADD_ALL_TESTS(test_custom_exts, 3);
2758 #endif
2759     ADD_ALL_TESTS(test_serverinfo, 8);
2760     ADD_ALL_TESTS(test_export_key_mat, 4);
2761     ADD_ALL_TESTS(test_ssl_clear, 2);
2762
2763     testresult = run_tests(argv[0]);
2764
2765     bio_s_mempacket_test_free();
2766
2767     return testresult;
2768 }