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