9e3326d2e8dfff39185e783601fac856e425ded1
[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 #ifndef OPENSSL_NO_OCSP
27 static const unsigned char orespder[] = "Dummy OCSP Response";
28 static int ocsp_server_called = 0;
29 static int ocsp_client_called = 0;
30
31 static int cdummyarg = 1;
32 static X509 *ocspcert = NULL;
33 #endif
34
35 #define NUM_EXTRA_CERTS 40
36
37 static int execute_test_large_message(const SSL_METHOD *smeth,
38                                       const SSL_METHOD *cmeth, int read_ahead)
39 {
40     SSL_CTX *cctx = NULL, *sctx = NULL;
41     SSL *clientssl = NULL, *serverssl = NULL;
42     int testresult = 0;
43     int i;
44     BIO *certbio = BIO_new_file(cert, "r");
45     X509 *chaincert = NULL;
46     int certlen;
47
48     if (certbio == NULL) {
49         printf("Can't load the certficate file\n");
50         goto end;
51     }
52     chaincert = PEM_read_bio_X509(certbio, NULL, NULL, NULL);
53     BIO_free(certbio);
54     certbio = NULL;
55     if (chaincert == NULL) {
56         printf("Unable to load certificate for chain\n");
57         goto end;
58     }
59
60     if (!create_ssl_ctx_pair(smeth, cmeth, &sctx,
61                              &cctx, cert, privkey)) {
62         printf("Unable to create SSL_CTX pair\n");
63         goto end;
64     }
65
66     if(read_ahead) {
67         /*
68          * Test that read_ahead works correctly when dealing with large
69          * records
70          */
71         SSL_CTX_set_read_ahead(cctx, 1);
72     }
73
74     /*
75      * We assume the supplied certificate is big enough so that if we add
76      * NUM_EXTRA_CERTS it will make the overall message large enough. The
77      * default buffer size is requested to be 16k, but due to the way BUF_MEM
78      * works, it ends up allocing a little over 21k (16 * 4/3). So, in this test
79      * we need to have a message larger than that.
80      */
81     certlen = i2d_X509(chaincert, NULL);
82     OPENSSL_assert((certlen * NUM_EXTRA_CERTS)
83                    > ((SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3));
84     for (i = 0; i < NUM_EXTRA_CERTS; i++) {
85         if (!X509_up_ref(chaincert)) {
86             printf("Unable to up ref cert\n");
87             goto end;
88         }
89         if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
90             printf("Unable to add extra chain cert %d\n", i);
91             X509_free(chaincert);
92             goto end;
93         }
94     }
95
96     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
97         printf("Unable to create SSL objects\n");
98         goto end;
99     }
100
101     if (!create_ssl_connection(serverssl, clientssl)) {
102         printf("Unable to create SSL connection\n");
103         goto end;
104     }
105
106     /*
107      * Calling SSL_clear() first is not required but this tests that SSL_clear()
108      * doesn't leak (when using enable-crypto-mdebug).
109      */
110     if (!SSL_clear(serverssl)) {
111         printf("Unexpected failure from SSL_clear()\n");
112         goto end;
113     }
114
115     testresult = 1;
116  end:
117     X509_free(chaincert);
118     SSL_free(serverssl);
119     SSL_free(clientssl);
120     SSL_CTX_free(sctx);
121     SSL_CTX_free(cctx);
122
123     return testresult;
124 }
125
126 static int test_large_message_tls(void)
127 {
128     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
129                                       0);
130 }
131
132 static int test_large_message_tls_read_ahead(void)
133 {
134     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
135                                       1);
136 }
137
138 #ifndef OPENSSL_NO_DTLS
139 static int test_large_message_dtls(void)
140 {
141     /*
142      * read_ahead is not relevant to DTLS because DTLS always acts as if
143      * read_ahead is set.
144      */
145     return execute_test_large_message(DTLS_server_method(),
146                                       DTLS_client_method(), 0);
147 }
148 #endif
149
150 #ifndef OPENSSL_NO_OCSP
151 static int ocsp_server_cb(SSL *s, void *arg)
152 {
153     int *argi = (int *)arg;
154     unsigned char *orespdercopy = NULL;
155     STACK_OF(OCSP_RESPID) *ids = NULL;
156     OCSP_RESPID *id = NULL;
157
158     if (*argi == 2) {
159         /* In this test we are expecting exactly 1 OCSP_RESPID */
160         SSL_get_tlsext_status_ids(s, &ids);
161         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
162             return SSL_TLSEXT_ERR_ALERT_FATAL;
163
164         id = sk_OCSP_RESPID_value(ids, 0);
165         if (id == NULL || !OCSP_RESPID_match(id, ocspcert))
166             return SSL_TLSEXT_ERR_ALERT_FATAL;
167     } else if (*argi != 1) {
168         return SSL_TLSEXT_ERR_ALERT_FATAL;
169     }
170
171
172     orespdercopy = OPENSSL_memdup(orespder, sizeof(orespder));
173     if (orespdercopy == NULL)
174         return SSL_TLSEXT_ERR_ALERT_FATAL;
175
176     SSL_set_tlsext_status_ocsp_resp(s, orespdercopy, sizeof(orespder));
177
178     ocsp_server_called = 1;
179
180     return SSL_TLSEXT_ERR_OK;
181 }
182
183 static int ocsp_client_cb(SSL *s, void *arg)
184 {
185     int *argi = (int *)arg;
186     const unsigned char *respderin;
187     size_t len;
188
189     if (*argi != 1 && *argi != 2)
190         return 0;
191
192     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
193
194     if (memcmp(orespder, respderin, len) != 0)
195         return 0;
196
197     ocsp_client_called = 1;
198
199     return 1;
200 }
201
202 static int test_tlsext_status_type(void)
203 {
204     SSL_CTX *cctx = NULL, *sctx = NULL;
205     SSL *clientssl = NULL, *serverssl = NULL;
206     int testresult = 0;
207     STACK_OF(OCSP_RESPID) *ids = NULL;
208     OCSP_RESPID *id = NULL;
209     BIO *certbio = NULL;
210
211     if (!create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(), &sctx,
212                              &cctx, cert, privkey)) {
213         printf("Unable to create SSL_CTX pair\n");
214         return 0;
215     }
216
217     if (SSL_CTX_get_tlsext_status_type(cctx) != -1) {
218         printf("Unexpected initial value for "
219                "SSL_CTX_get_tlsext_status_type()\n");
220         goto end;
221     }
222
223     /* First just do various checks getting and setting tlsext_status_type */
224
225     clientssl = SSL_new(cctx);
226     if (SSL_get_tlsext_status_type(clientssl) != -1) {
227         printf("Unexpected initial value for SSL_get_tlsext_status_type()\n");
228         goto end;
229     }
230
231     if (!SSL_set_tlsext_status_type(clientssl, TLSEXT_STATUSTYPE_ocsp)) {
232         printf("Unexpected fail for SSL_set_tlsext_status_type()\n");
233         goto end;
234     }
235
236     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp) {
237         printf("Unexpected result for SSL_get_tlsext_status_type()\n");
238         goto end;
239     }
240
241     SSL_free(clientssl);
242     clientssl = NULL;
243
244     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)) {
245         printf("Unexpected fail for SSL_CTX_set_tlsext_status_type()\n");
246         goto end;
247     }
248
249     if (SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp) {
250         printf("Unexpected result for SSL_CTX_get_tlsext_status_type()\n");
251         goto end;
252     }
253
254     clientssl = SSL_new(cctx);
255
256     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp) {
257         printf("Unexpected result for SSL_get_tlsext_status_type() (test 2)\n");
258         goto end;
259     }
260
261     SSL_free(clientssl);
262     clientssl = NULL;
263
264     /*
265      * Now actually do a handshake and check OCSP information is exchanged and
266      * the callbacks get called
267      */
268
269     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
270     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
271     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
272     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
273
274     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
275         printf("Unable to create SSL objects\n");
276         goto end;
277     }
278
279     if (!create_ssl_connection(serverssl, clientssl)) {
280         printf("Unable to create SSL connection\n");
281         goto end;
282     }
283
284     if (!ocsp_client_called || !ocsp_server_called) {
285         printf("OCSP callbacks not called\n");
286         goto end;
287     }
288
289     SSL_free(serverssl);
290     SSL_free(clientssl);
291     serverssl = NULL;
292     clientssl = NULL;
293
294     /* Try again but this time force the server side callback to fail */
295     ocsp_client_called = 0;
296     ocsp_server_called = 0;
297     cdummyarg = 0;
298
299     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
300         printf("Unable to create SSL objects\n");
301         goto end;
302     }
303
304     /* This should fail because the callback will fail */
305     if (create_ssl_connection(serverssl, clientssl)) {
306         printf("Unexpected success creating the connection\n");
307         goto end;
308     }
309
310     if (ocsp_client_called || ocsp_server_called) {
311         printf("OCSP callbacks successfully called unexpectedly\n");
312         goto end;
313     }
314
315     SSL_free(serverssl);
316     SSL_free(clientssl);
317     serverssl = NULL;
318     clientssl = NULL;
319
320     /*
321      * This time we'll get the client to send an OCSP_RESPID that it will
322      * accept.
323      */
324     ocsp_client_called = 0;
325     ocsp_server_called = 0;
326     cdummyarg = 2;
327
328     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
329         printf("Unable to create SSL objects\n");
330         goto end;
331     }
332
333     /*
334      * We'll just use any old cert for this test - it doesn't have to be an OCSP
335      * specifc one. We'll use the server cert.
336      */
337     certbio = BIO_new_file(cert, "r");
338     if (certbio == NULL) {
339         printf("Can't load the certficate file\n");
340         goto end;
341     }
342     id = OCSP_RESPID_new();
343     ids = sk_OCSP_RESPID_new_null();
344     ocspcert = PEM_read_bio_X509(certbio, NULL, NULL, NULL);
345     if (id == NULL || ids == NULL || ocspcert == NULL
346             || !OCSP_RESPID_set_by_key(id, ocspcert)
347             || !sk_OCSP_RESPID_push(ids, id)) {
348         printf("Unable to set OCSP_RESPIDs\n");
349         goto end;
350     }
351     id = NULL;
352     SSL_set_tlsext_status_ids(clientssl, ids);
353     /* Control has been transferred */
354     ids = NULL;
355
356     BIO_free(certbio);
357     certbio = NULL;
358
359     if (!create_ssl_connection(serverssl, clientssl)) {
360         printf("Unable to create SSL connection\n");
361         goto end;
362     }
363
364     if (!ocsp_client_called || !ocsp_server_called) {
365         printf("OCSP callbacks not called\n");
366         goto end;
367     }
368
369     testresult = 1;
370
371  end:
372     SSL_free(serverssl);
373     SSL_free(clientssl);
374     SSL_CTX_free(sctx);
375     SSL_CTX_free(cctx);
376     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
377     OCSP_RESPID_free(id);
378     BIO_free(certbio);
379     X509_free(ocspcert);
380     ocspcert = NULL;
381
382     return testresult;
383 }
384 #endif
385
386 typedef struct ssl_session_test_fixture {
387     const char *test_case_name;
388     int use_ext_cache;
389     int use_int_cache;
390 } SSL_SESSION_TEST_FIXTURE;
391
392 static int new_called = 0, remove_called = 0;
393
394 static SSL_SESSION_TEST_FIXTURE
395 ssl_session_set_up(const char *const test_case_name)
396 {
397     SSL_SESSION_TEST_FIXTURE fixture;
398
399     fixture.test_case_name = test_case_name;
400     fixture.use_ext_cache = 1;
401     fixture.use_int_cache = 1;
402
403     new_called = remove_called = 0;
404
405     return fixture;
406 }
407
408 static void ssl_session_tear_down(SSL_SESSION_TEST_FIXTURE fixture)
409 {
410 }
411
412 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
413 {
414     new_called++;
415
416     return 1;
417 }
418
419 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
420 {
421     remove_called++;
422 }
423
424 static int execute_test_session(SSL_SESSION_TEST_FIXTURE fix)
425 {
426     SSL_CTX *sctx = NULL, *cctx = NULL;
427     SSL *serverssl1 = NULL, *clientssl1 = NULL;
428     SSL *serverssl2 = NULL, *clientssl2 = NULL;
429 #ifndef OPENSSL_NO_TLS1_1
430     SSL *serverssl3 = NULL, *clientssl3 = NULL;
431 #endif
432     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
433     int testresult = 0;
434
435     if (!create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(), &sctx,
436                              &cctx, cert, privkey)) {
437         printf("Unable to create SSL_CTX pair\n");
438         return 0;
439     }
440
441 #ifndef OPENSSL_NO_TLS1_2
442     /* Only allow TLS1.2 so we can force a connection failure later */
443     SSL_CTX_set_min_proto_version(cctx, TLS1_2_VERSION);
444 #endif
445
446     /*
447      * TODO(TLS1.3): Test temporarily disabled for TLS1.3 until we've
448      * implemented session resumption.
449      */
450     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
451
452     /* Set up session cache */
453     if (fix.use_ext_cache) {
454         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
455         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
456     }
457     if (fix.use_int_cache) {
458         /* Also covers instance where both are set */
459         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
460     } else {
461         SSL_CTX_set_session_cache_mode(cctx,
462                                        SSL_SESS_CACHE_CLIENT
463                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
464     }
465
466     if (!create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1, NULL,
467                                NULL)) {
468         printf("Unable to create SSL objects\n");
469         goto end;
470     }
471
472     if (!create_ssl_connection(serverssl1, clientssl1)) {
473         printf("Unable to create SSL connection\n");
474         goto end;
475     }
476     sess1 = SSL_get1_session(clientssl1);
477     if (sess1 == NULL) {
478         printf("Unexpected NULL session\n");
479         goto end;
480     }
481
482     if (fix.use_int_cache && SSL_CTX_add_session(cctx, sess1)) {
483         /* Should have failed because it should already be in the cache */
484         printf("Unexpected success adding session to cache\n");
485         goto end;
486     }
487
488     if (fix.use_ext_cache && (new_called != 1 || remove_called != 0)) {
489         printf("Session not added to cache\n");
490         goto end;
491     }
492
493     if (!create_ssl_objects(sctx, cctx, &serverssl2, &clientssl2, NULL, NULL)) {
494         printf("Unable to create second SSL objects\n");
495         goto end;
496     }
497
498     if (!create_ssl_connection(serverssl2, clientssl2)) {
499         printf("Unable to create second SSL connection\n");
500         goto end;
501     }
502
503     sess2 = SSL_get1_session(clientssl2);
504     if (sess2 == NULL) {
505         printf("Unexpected NULL session from clientssl2\n");
506         goto end;
507     }
508
509     if (fix.use_ext_cache && (new_called != 2 || remove_called != 0)) {
510         printf("Remove session callback unexpectedly called\n");
511         goto end;
512     }
513
514     /*
515      * This should clear sess2 from the cache because it is a "bad" session. See
516      * SSL_set_session() documentation.
517      */
518     if (!SSL_set_session(clientssl2, sess1)) {
519         printf("Unexpected failure setting session\n");
520         goto end;
521     }
522
523     if (fix.use_ext_cache && (new_called != 2 || remove_called != 1)) {
524         printf("Failed to call callback to remove session\n");
525         goto end;
526     }
527
528
529     if (SSL_get_session(clientssl2) != sess1) {
530         printf("Unexpected session found\n");
531         goto end;
532     }
533
534     if (fix.use_int_cache) {
535         if (!SSL_CTX_add_session(cctx, sess2)) {
536             /*
537              * Should have succeeded because it should not already be in the cache
538              */
539             printf("Unexpected failure adding session to cache\n");
540             goto end;
541         }
542
543         if (!SSL_CTX_remove_session(cctx, sess2)) {
544             printf("Unexpected failure removing session from cache\n");
545             goto end;
546         }
547
548         /* This is for the purposes of internal cache testing...ignore the
549          * counter for external cache
550          */
551         if (fix.use_ext_cache)
552             remove_called--;
553     }
554
555     /* This shouldn't be in the cache so should fail */
556     if (SSL_CTX_remove_session(cctx, sess2)) {
557         printf("Unexpected success removing session from cache\n");
558         goto end;
559     }
560
561     if (fix.use_ext_cache && (new_called != 2 || remove_called != 2)) {
562         printf("Failed to call callback to remove session #2\n");
563         goto end;
564     }
565
566 #if !defined(OPENSSL_NO_TLS1_1) && !defined(OPENSSL_NO_TLS1_2)
567     /* Force a connection failure */
568     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
569
570     if (!create_ssl_objects(sctx, cctx, &serverssl3, &clientssl3, NULL, NULL)) {
571         printf("Unable to create third SSL objects\n");
572         goto end;
573     }
574
575     if (!SSL_set_session(clientssl3, sess1)) {
576         printf("Unable to set session for third connection\n");
577         goto end;
578     }
579
580     /* This should fail because of the mismatched protocol versions */
581     if (create_ssl_connection(serverssl3, clientssl3)) {
582         printf("Unable to create third SSL connection\n");
583         goto end;
584     }
585
586
587     /* We should have automatically removed the session from the cache */
588     if (fix.use_ext_cache && (new_called != 2 || remove_called != 3)) {
589         printf("Failed to call callback to remove session #2\n");
590         goto end;
591     }
592
593     if (fix.use_int_cache && !SSL_CTX_add_session(cctx, sess2)) {
594         /*
595          * Should have succeeded because it should not already be in the cache
596          */
597         printf("Unexpected failure adding session to cache #2\n");
598         goto end;
599     }
600 #endif
601
602     testresult = 1;
603
604  end:
605     SSL_free(serverssl1);
606     SSL_free(clientssl1);
607     SSL_free(serverssl2);
608     SSL_free(clientssl2);
609 #ifndef OPENSSL_NO_TLS1_1
610     SSL_free(serverssl3);
611     SSL_free(clientssl3);
612 #endif
613     SSL_SESSION_free(sess1);
614     SSL_SESSION_free(sess2);
615     /*
616      * Check if we need to remove any sessions up-refed for the external cache
617      */
618     if (new_called >= 1)
619         SSL_SESSION_free(sess1);
620     if (new_called >= 2)
621         SSL_SESSION_free(sess2);
622     SSL_CTX_free(sctx);
623     SSL_CTX_free(cctx);
624
625     return testresult;
626 }
627
628 static int test_session_with_only_int_cache(void)
629 {
630     SETUP_TEST_FIXTURE(SSL_SESSION_TEST_FIXTURE, ssl_session_set_up);
631
632     fixture.use_ext_cache = 0;
633
634     EXECUTE_TEST(execute_test_session, ssl_session_tear_down);
635 }
636
637 static int test_session_with_only_ext_cache(void)
638 {
639     SETUP_TEST_FIXTURE(SSL_SESSION_TEST_FIXTURE, ssl_session_set_up);
640
641     fixture.use_int_cache = 0;
642
643     EXECUTE_TEST(execute_test_session, ssl_session_tear_down);
644 }
645
646 static int test_session_with_both_cache(void)
647 {
648     SETUP_TEST_FIXTURE(SSL_SESSION_TEST_FIXTURE, ssl_session_set_up);
649
650     EXECUTE_TEST(execute_test_session, ssl_session_tear_down);
651 }
652
653 #define USE_NULL    0
654 #define USE_BIO_1   1
655 #define USE_BIO_2   2
656
657 #define TOTAL_SSL_SET_BIO_TESTS (3 * 3 * 3 * 3)
658
659 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
660 {
661     switch (type) {
662     case USE_NULL:
663         *res = NULL;
664         break;
665     case USE_BIO_1:
666         *res = bio1;
667         break;
668     case USE_BIO_2:
669         *res = bio2;
670         break;
671     }
672 }
673
674 static int test_ssl_set_bio(int idx)
675 {
676     SSL_CTX *ctx = SSL_CTX_new(TLS_method());
677     BIO *bio1 = NULL;
678     BIO *bio2 = NULL;
679     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
680     SSL *ssl = NULL;
681     int initrbio, initwbio, newrbio, newwbio;
682     int testresult = 0;
683
684     if (ctx == NULL) {
685         printf("Failed to allocate SSL_CTX\n");
686         goto end;
687     }
688
689     ssl = SSL_new(ctx);
690     if (ssl == NULL) {
691         printf("Failed to allocate SSL object\n");
692         goto end;
693     }
694
695     initrbio = idx % 3;
696     idx /= 3;
697     initwbio = idx % 3;
698     idx /= 3;
699     newrbio = idx % 3;
700     idx /= 3;
701     newwbio = idx;
702     OPENSSL_assert(newwbio <= 2);
703
704     if (initrbio == USE_BIO_1 || initwbio == USE_BIO_1 || newrbio == USE_BIO_1
705             || newwbio == USE_BIO_1) {
706         bio1 = BIO_new(BIO_s_mem());
707         if (bio1 == NULL) {
708             printf("Failed to allocate bio1\n");
709             goto end;
710         }
711     }
712
713     if (initrbio == USE_BIO_2 || initwbio == USE_BIO_2 || newrbio == USE_BIO_2
714             || newwbio == USE_BIO_2) {
715         bio2 = BIO_new(BIO_s_mem());
716         if (bio2 == NULL) {
717             printf("Failed to allocate bio2\n");
718             goto end;
719         }
720     }
721
722     setupbio(&irbio, bio1, bio2, initrbio);
723     setupbio(&iwbio, bio1, bio2, initwbio);
724
725     /*
726      * We want to maintain our own refs to these BIO, so do an up ref for each
727      * BIO that will have ownersip transferred in the SSL_set_bio() call
728      */
729     if (irbio != NULL)
730         BIO_up_ref(irbio);
731     if (iwbio != NULL && iwbio != irbio)
732         BIO_up_ref(iwbio);
733
734     SSL_set_bio(ssl, irbio, iwbio);
735
736     setupbio(&nrbio, bio1, bio2, newrbio);
737     setupbio(&nwbio, bio1, bio2, newwbio);
738
739     /*
740      * We will (maybe) transfer ownership again so do more up refs.
741      * SSL_set_bio() has some really complicated ownership rules where BIOs have
742      * already been set!
743      */
744     if (nrbio != NULL && nrbio != irbio && (nwbio != iwbio || nrbio != nwbio))
745         BIO_up_ref(nrbio);
746     if (nwbio != NULL && nwbio != nrbio && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
747         BIO_up_ref(nwbio);
748
749     SSL_set_bio(ssl, nrbio, nwbio);
750
751     testresult = 1;
752
753  end:
754     SSL_free(ssl);
755     BIO_free(bio1);
756     BIO_free(bio2);
757     /*
758      * This test is checking that the ref counting for SSL_set_bio is correct.
759      * If we get here and we did too many frees then we will fail in the above
760      * functions. If we haven't done enough then this will only be detected in
761      * a crypto-mdebug build
762      */
763     SSL_CTX_free(ctx);
764
765     return testresult;
766 }
767
768 typedef struct ssl_bio_test_fixture {
769     const char *test_case_name;
770     int pop_ssl;
771     enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } change_bio;
772 } SSL_BIO_TEST_FIXTURE;
773
774 static SSL_BIO_TEST_FIXTURE ssl_bio_set_up(const char *const test_case_name)
775 {
776     SSL_BIO_TEST_FIXTURE fixture;
777
778     fixture.test_case_name = test_case_name;
779     fixture.pop_ssl = 0;
780     fixture.change_bio = NO_BIO_CHANGE;
781
782     return fixture;
783 }
784
785 static void ssl_bio_tear_down(SSL_BIO_TEST_FIXTURE fixture)
786 {
787 }
788
789 static int execute_test_ssl_bio(SSL_BIO_TEST_FIXTURE fix)
790 {
791     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
792     SSL_CTX *ctx = SSL_CTX_new(TLS_method());
793     SSL *ssl = NULL;
794     int testresult = 0;
795
796     if (ctx == NULL) {
797         printf("Failed to allocate SSL_CTX\n");
798         return 0;
799     }
800
801     ssl = SSL_new(ctx);
802     if (ssl == NULL) {
803         printf("Failed to allocate SSL object\n");
804         goto end;
805     }
806
807     sslbio = BIO_new(BIO_f_ssl());
808     membio1 = BIO_new(BIO_s_mem());
809
810     if (sslbio == NULL || membio1 == NULL) {
811         printf("Malloc failure creating BIOs\n");
812         goto end;
813     }
814
815     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
816
817     /*
818      * If anything goes wrong here then we could leak memory, so this will
819      * be caught in a crypto-mdebug build
820      */
821     BIO_push(sslbio, membio1);
822
823     /* Verify chaning the rbio/wbio directly does not cause leaks */
824     if (fix.change_bio != NO_BIO_CHANGE) {
825         membio2 = BIO_new(BIO_s_mem());
826         if (membio2 == NULL) {
827             printf("Malloc failure creating membio2\n");
828             goto end;
829         }
830         if (fix.change_bio == CHANGE_RBIO)
831             SSL_set0_rbio(ssl, membio2);
832         else
833             SSL_set0_wbio(ssl, membio2);
834     }
835     ssl = NULL;
836
837     if (fix.pop_ssl)
838         BIO_pop(sslbio);
839     else
840         BIO_pop(membio1);
841
842     testresult = 1;
843  end:
844     BIO_free(membio1);
845     BIO_free(sslbio);
846     SSL_free(ssl);
847     SSL_CTX_free(ctx);
848
849     return testresult;
850 }
851
852 static int test_ssl_bio_pop_next_bio(void)
853 {
854     SETUP_TEST_FIXTURE(SSL_BIO_TEST_FIXTURE, ssl_bio_set_up);
855
856     EXECUTE_TEST(execute_test_ssl_bio, ssl_bio_tear_down);
857 }
858
859 static int test_ssl_bio_pop_ssl_bio(void)
860 {
861     SETUP_TEST_FIXTURE(SSL_BIO_TEST_FIXTURE, ssl_bio_set_up);
862
863     fixture.pop_ssl = 1;
864
865     EXECUTE_TEST(execute_test_ssl_bio, ssl_bio_tear_down);
866 }
867
868 static int test_ssl_bio_change_rbio(void)
869 {
870     SETUP_TEST_FIXTURE(SSL_BIO_TEST_FIXTURE, ssl_bio_set_up);
871
872     fixture.change_bio = CHANGE_RBIO;
873
874     EXECUTE_TEST(execute_test_ssl_bio, ssl_bio_tear_down);
875 }
876
877 static int test_ssl_bio_change_wbio(void)
878 {
879     SETUP_TEST_FIXTURE(SSL_BIO_TEST_FIXTURE, ssl_bio_set_up);
880
881     fixture.change_bio = CHANGE_WBIO;
882
883     EXECUTE_TEST(execute_test_ssl_bio, ssl_bio_tear_down);
884 }
885
886 typedef struct {
887     /* The list of sig algs */
888     const int *list;
889     /* The length of the list */
890     size_t listlen;
891     /* A sigalgs list in string format */
892     const char *liststr;
893     /* Whether setting the list should succeed */
894     int valid;
895     /* Whether creating a connection with the list should succeed */
896     int connsuccess;
897 } sigalgs_list;
898
899 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
900 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
901 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
902 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
903 static const int invalidlist2[] = {NID_sha256, NID_undef};
904 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
905 static const int invalidlist4[] = {NID_sha256};
906 static const sigalgs_list testsigalgs[] = {
907     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
908     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
909     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
910     {NULL, 0, "RSA+SHA256", 1, 1},
911     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
912     {NULL, 0, "ECDSA+SHA512", 1, 0},
913     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
914     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
915     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
916     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
917     {NULL, 0, "RSA", 0, 0},
918     {NULL, 0, "SHA256", 0, 0},
919     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
920     {NULL, 0, "Invalid", 0, 0}};
921
922 static int test_set_sigalgs(int idx)
923 {
924     SSL_CTX *cctx = NULL, *sctx = NULL;
925     SSL *clientssl = NULL, *serverssl = NULL;
926     int testresult = 0;
927     const sigalgs_list *curr;
928     int testctx;
929
930     /* Should never happen */
931     if ((size_t)idx >= OSSL_NELEM(testsigalgs) * 2)
932         return 0;
933
934     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
935     curr = testctx ? &testsigalgs[idx]
936                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
937
938     if (!create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(), &sctx,
939                              &cctx, cert, privkey)) {
940         printf("Unable to create SSL_CTX pair\n");
941         return 0;
942     }
943
944     /*
945      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
946      * for TLSv1.2 for now until we add a new API.
947      */
948     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
949
950     if (testctx) {
951         int ret;
952         if (curr->list != NULL)
953             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
954         else
955             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
956
957         if (!ret) {
958             if (curr->valid)
959                 printf("Unexpected failure setting sigalgs in SSL_CTX (%d)\n",
960                        idx);
961             else
962                 testresult = 1;
963             goto end;
964         }
965         if (!curr->valid) {
966             printf("Unexpected success setting sigalgs in SSL_CTX (%d)\n", idx);
967             goto end;
968         }
969     }
970
971     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
972         printf("Unable to create SSL objects\n");
973         goto end;
974     }
975
976     if (!testctx) {
977         int ret;
978
979         if (curr->list != NULL)
980             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
981         else
982             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
983         if (!ret) {
984             if (curr->valid)
985                 printf("Unexpected failure setting sigalgs in SSL (%d)\n", idx);
986             else
987                 testresult = 1;
988             goto end;
989         }
990         if (!curr->valid) {
991             printf("Unexpected success setting sigalgs in SSL (%d)\n", idx);
992             goto end;
993         }
994     }
995
996     if (curr->connsuccess != create_ssl_connection(serverssl, clientssl)) {
997         printf("Unexpected return value creating SSL connection (%d)\n", idx);
998         goto end;
999     }
1000
1001     testresult = 1;
1002
1003  end:
1004     SSL_free(serverssl);
1005     SSL_free(clientssl);
1006     SSL_CTX_free(sctx);
1007     SSL_CTX_free(cctx);
1008
1009     return testresult;
1010 }
1011
1012 int test_main(int argc, char *argv[])
1013 {
1014     int testresult = 1;
1015
1016     if (argc != 3) {
1017         printf("Invalid argument count\n");
1018         return 1;
1019     }
1020
1021     cert = argv[1];
1022     privkey = argv[2];
1023
1024     ADD_TEST(test_large_message_tls);
1025     ADD_TEST(test_large_message_tls_read_ahead);
1026 #ifndef OPENSSL_NO_DTLS
1027     ADD_TEST(test_large_message_dtls);
1028 #endif
1029 #ifndef OPENSSL_NO_OCSP
1030     ADD_TEST(test_tlsext_status_type);
1031 #endif
1032     ADD_TEST(test_session_with_only_int_cache);
1033     ADD_TEST(test_session_with_only_ext_cache);
1034     ADD_TEST(test_session_with_both_cache);
1035     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
1036     ADD_TEST(test_ssl_bio_pop_next_bio);
1037     ADD_TEST(test_ssl_bio_pop_ssl_bio);
1038     ADD_TEST(test_ssl_bio_change_rbio);
1039     ADD_TEST(test_ssl_bio_change_wbio);
1040     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
1041
1042     testresult = run_tests(argv[0]);
1043
1044     bio_s_mempacket_test_free();
1045
1046     return testresult;
1047 }