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