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