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