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