bio_ssl.c revision 296465
1/* ssl/bio_ssl.c */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <errno.h>
63#include <openssl/crypto.h>
64#include <openssl/bio.h>
65#include <openssl/err.h>
66#include <openssl/ssl.h>
67
68static int ssl_write(BIO *h, const char *buf, int num);
69static int ssl_read(BIO *h, char *buf, int size);
70static int ssl_puts(BIO *h, const char *str);
71static long ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2);
72static int ssl_new(BIO *h);
73static int ssl_free(BIO *data);
74static long ssl_callback_ctrl(BIO *h, int cmd, bio_info_cb *fp);
75typedef struct bio_ssl_st {
76    SSL *ssl;                   /* The ssl handle :-) */
77    /* re-negotiate every time the total number of bytes is this size */
78    int num_renegotiates;
79    unsigned long renegotiate_count;
80    unsigned long byte_count;
81    unsigned long renegotiate_timeout;
82    unsigned long last_time;
83} BIO_SSL;
84
85static BIO_METHOD methods_sslp = {
86    BIO_TYPE_SSL, "ssl",
87    ssl_write,
88    ssl_read,
89    ssl_puts,
90    NULL,                       /* ssl_gets, */
91    ssl_ctrl,
92    ssl_new,
93    ssl_free,
94    ssl_callback_ctrl,
95};
96
97BIO_METHOD *BIO_f_ssl(void)
98{
99    return (&methods_sslp);
100}
101
102static int ssl_new(BIO *bi)
103{
104    BIO_SSL *bs;
105
106    bs = (BIO_SSL *)OPENSSL_malloc(sizeof(BIO_SSL));
107    if (bs == NULL) {
108        BIOerr(BIO_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
109        return (0);
110    }
111    memset(bs, 0, sizeof(BIO_SSL));
112    bi->init = 0;
113    bi->ptr = (char *)bs;
114    bi->flags = 0;
115    return (1);
116}
117
118static int ssl_free(BIO *a)
119{
120    BIO_SSL *bs;
121
122    if (a == NULL)
123        return (0);
124    bs = (BIO_SSL *)a->ptr;
125    if (bs->ssl != NULL)
126        SSL_shutdown(bs->ssl);
127    if (a->shutdown) {
128        if (a->init && (bs->ssl != NULL))
129            SSL_free(bs->ssl);
130        a->init = 0;
131        a->flags = 0;
132    }
133    if (a->ptr != NULL)
134        OPENSSL_free(a->ptr);
135    return (1);
136}
137
138static int ssl_read(BIO *b, char *out, int outl)
139{
140    int ret = 1;
141    BIO_SSL *sb;
142    SSL *ssl;
143    int retry_reason = 0;
144    int r = 0;
145
146    if (out == NULL)
147        return (0);
148    sb = (BIO_SSL *)b->ptr;
149    ssl = sb->ssl;
150
151    BIO_clear_retry_flags(b);
152
153#if 0
154    if (!SSL_is_init_finished(ssl)) {
155/*              ret=SSL_do_handshake(ssl); */
156        if (ret > 0) {
157
158            outflags = (BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
159            ret = -1;
160            goto end;
161        }
162    }
163#endif
164/*      if (ret > 0) */
165    ret = SSL_read(ssl, out, outl);
166
167    switch (SSL_get_error(ssl, ret)) {
168    case SSL_ERROR_NONE:
169        if (ret <= 0)
170            break;
171        if (sb->renegotiate_count > 0) {
172            sb->byte_count += ret;
173            if (sb->byte_count > sb->renegotiate_count) {
174                sb->byte_count = 0;
175                sb->num_renegotiates++;
176                SSL_renegotiate(ssl);
177                r = 1;
178            }
179        }
180        if ((sb->renegotiate_timeout > 0) && (!r)) {
181            unsigned long tm;
182
183            tm = (unsigned long)time(NULL);
184            if (tm > sb->last_time + sb->renegotiate_timeout) {
185                sb->last_time = tm;
186                sb->num_renegotiates++;
187                SSL_renegotiate(ssl);
188            }
189        }
190
191        break;
192    case SSL_ERROR_WANT_READ:
193        BIO_set_retry_read(b);
194        break;
195    case SSL_ERROR_WANT_WRITE:
196        BIO_set_retry_write(b);
197        break;
198    case SSL_ERROR_WANT_X509_LOOKUP:
199        BIO_set_retry_special(b);
200        retry_reason = BIO_RR_SSL_X509_LOOKUP;
201        break;
202    case SSL_ERROR_WANT_ACCEPT:
203        BIO_set_retry_special(b);
204        retry_reason = BIO_RR_ACCEPT;
205        break;
206    case SSL_ERROR_WANT_CONNECT:
207        BIO_set_retry_special(b);
208        retry_reason = BIO_RR_CONNECT;
209        break;
210    case SSL_ERROR_SYSCALL:
211    case SSL_ERROR_SSL:
212    case SSL_ERROR_ZERO_RETURN:
213    default:
214        break;
215    }
216
217    b->retry_reason = retry_reason;
218    return (ret);
219}
220
221static int ssl_write(BIO *b, const char *out, int outl)
222{
223    int ret, r = 0;
224    int retry_reason = 0;
225    SSL *ssl;
226    BIO_SSL *bs;
227
228    if (out == NULL)
229        return (0);
230    bs = (BIO_SSL *)b->ptr;
231    ssl = bs->ssl;
232
233    BIO_clear_retry_flags(b);
234
235    /*
236     * ret=SSL_do_handshake(ssl); if (ret > 0)
237     */
238    ret = SSL_write(ssl, out, outl);
239
240    switch (SSL_get_error(ssl, ret)) {
241    case SSL_ERROR_NONE:
242        if (ret <= 0)
243            break;
244        if (bs->renegotiate_count > 0) {
245            bs->byte_count += ret;
246            if (bs->byte_count > bs->renegotiate_count) {
247                bs->byte_count = 0;
248                bs->num_renegotiates++;
249                SSL_renegotiate(ssl);
250                r = 1;
251            }
252        }
253        if ((bs->renegotiate_timeout > 0) && (!r)) {
254            unsigned long tm;
255
256            tm = (unsigned long)time(NULL);
257            if (tm > bs->last_time + bs->renegotiate_timeout) {
258                bs->last_time = tm;
259                bs->num_renegotiates++;
260                SSL_renegotiate(ssl);
261            }
262        }
263        break;
264    case SSL_ERROR_WANT_WRITE:
265        BIO_set_retry_write(b);
266        break;
267    case SSL_ERROR_WANT_READ:
268        BIO_set_retry_read(b);
269        break;
270    case SSL_ERROR_WANT_X509_LOOKUP:
271        BIO_set_retry_special(b);
272        retry_reason = BIO_RR_SSL_X509_LOOKUP;
273        break;
274    case SSL_ERROR_WANT_CONNECT:
275        BIO_set_retry_special(b);
276        retry_reason = BIO_RR_CONNECT;
277    case SSL_ERROR_SYSCALL:
278    case SSL_ERROR_SSL:
279    default:
280        break;
281    }
282
283    b->retry_reason = retry_reason;
284    return (ret);
285}
286
287static long ssl_ctrl(BIO *b, int cmd, long num, void *ptr)
288{
289    SSL **sslp, *ssl;
290    BIO_SSL *bs;
291    BIO *dbio, *bio;
292    long ret = 1;
293
294    bs = (BIO_SSL *)b->ptr;
295    ssl = bs->ssl;
296    if ((ssl == NULL) && (cmd != BIO_C_SET_SSL))
297        return (0);
298    switch (cmd) {
299    case BIO_CTRL_RESET:
300        SSL_shutdown(ssl);
301
302        if (ssl->handshake_func == ssl->method->ssl_connect)
303            SSL_set_connect_state(ssl);
304        else if (ssl->handshake_func == ssl->method->ssl_accept)
305            SSL_set_accept_state(ssl);
306
307        SSL_clear(ssl);
308
309        if (b->next_bio != NULL)
310            ret = BIO_ctrl(b->next_bio, cmd, num, ptr);
311        else if (ssl->rbio != NULL)
312            ret = BIO_ctrl(ssl->rbio, cmd, num, ptr);
313        else
314            ret = 1;
315        break;
316    case BIO_CTRL_INFO:
317        ret = 0;
318        break;
319    case BIO_C_SSL_MODE:
320        if (num)                /* client mode */
321            SSL_set_connect_state(ssl);
322        else
323            SSL_set_accept_state(ssl);
324        break;
325    case BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT:
326        ret = bs->renegotiate_timeout;
327        if (num < 60)
328            num = 5;
329        bs->renegotiate_timeout = (unsigned long)num;
330        bs->last_time = (unsigned long)time(NULL);
331        break;
332    case BIO_C_SET_SSL_RENEGOTIATE_BYTES:
333        ret = bs->renegotiate_count;
334        if ((long)num >= 512)
335            bs->renegotiate_count = (unsigned long)num;
336        break;
337    case BIO_C_GET_SSL_NUM_RENEGOTIATES:
338        ret = bs->num_renegotiates;
339        break;
340    case BIO_C_SET_SSL:
341        if (ssl != NULL) {
342            ssl_free(b);
343            if (!ssl_new(b))
344                return 0;
345        }
346        b->shutdown = (int)num;
347        ssl = (SSL *)ptr;
348        ((BIO_SSL *)b->ptr)->ssl = ssl;
349        bio = SSL_get_rbio(ssl);
350        if (bio != NULL) {
351            if (b->next_bio != NULL)
352                BIO_push(bio, b->next_bio);
353            b->next_bio = bio;
354            CRYPTO_add(&bio->references, 1, CRYPTO_LOCK_BIO);
355        }
356        b->init = 1;
357        break;
358    case BIO_C_GET_SSL:
359        if (ptr != NULL) {
360            sslp = (SSL **)ptr;
361            *sslp = ssl;
362        } else
363            ret = 0;
364        break;
365    case BIO_CTRL_GET_CLOSE:
366        ret = b->shutdown;
367        break;
368    case BIO_CTRL_SET_CLOSE:
369        b->shutdown = (int)num;
370        break;
371    case BIO_CTRL_WPENDING:
372        ret = BIO_ctrl(ssl->wbio, cmd, num, ptr);
373        break;
374    case BIO_CTRL_PENDING:
375        ret = SSL_pending(ssl);
376        if (ret == 0)
377            ret = BIO_pending(ssl->rbio);
378        break;
379    case BIO_CTRL_FLUSH:
380        BIO_clear_retry_flags(b);
381        ret = BIO_ctrl(ssl->wbio, cmd, num, ptr);
382        BIO_copy_next_retry(b);
383        break;
384    case BIO_CTRL_PUSH:
385        if ((b->next_bio != NULL) && (b->next_bio != ssl->rbio)) {
386            SSL_set_bio(ssl, b->next_bio, b->next_bio);
387            CRYPTO_add(&b->next_bio->references, 1, CRYPTO_LOCK_BIO);
388        }
389        break;
390    case BIO_CTRL_POP:
391        /* ugly bit of a hack */
392        if (ssl->rbio != ssl->wbio) { /* we are in trouble :-( */
393            BIO_free_all(ssl->wbio);
394        }
395        if (b->next_bio != NULL) {
396            CRYPTO_add(&b->next_bio->references, 1, CRYPTO_LOCK_BIO);
397        }
398        ssl->wbio = NULL;
399        ssl->rbio = NULL;
400        break;
401    case BIO_C_DO_STATE_MACHINE:
402        BIO_clear_retry_flags(b);
403
404        b->retry_reason = 0;
405        ret = (int)SSL_do_handshake(ssl);
406
407        switch (SSL_get_error(ssl, (int)ret)) {
408        case SSL_ERROR_WANT_READ:
409            BIO_set_flags(b, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
410            break;
411        case SSL_ERROR_WANT_WRITE:
412            BIO_set_flags(b, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
413            break;
414        case SSL_ERROR_WANT_CONNECT:
415            BIO_set_flags(b, BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY);
416            b->retry_reason = b->next_bio->retry_reason;
417            break;
418        default:
419            break;
420        }
421        break;
422    case BIO_CTRL_DUP:
423        dbio = (BIO *)ptr;
424        if (((BIO_SSL *)dbio->ptr)->ssl != NULL)
425            SSL_free(((BIO_SSL *)dbio->ptr)->ssl);
426        ((BIO_SSL *)dbio->ptr)->ssl = SSL_dup(ssl);
427        ((BIO_SSL *)dbio->ptr)->renegotiate_count =
428            ((BIO_SSL *)b->ptr)->renegotiate_count;
429        ((BIO_SSL *)dbio->ptr)->byte_count = ((BIO_SSL *)b->ptr)->byte_count;
430        ((BIO_SSL *)dbio->ptr)->renegotiate_timeout =
431            ((BIO_SSL *)b->ptr)->renegotiate_timeout;
432        ((BIO_SSL *)dbio->ptr)->last_time = ((BIO_SSL *)b->ptr)->last_time;
433        ret = (((BIO_SSL *)dbio->ptr)->ssl != NULL);
434        break;
435    case BIO_C_GET_FD:
436        ret = BIO_ctrl(ssl->rbio, cmd, num, ptr);
437        break;
438    case BIO_CTRL_SET_CALLBACK:
439        {
440#if 0                           /* FIXME: Should this be used? -- Richard
441                                 * Levitte */
442            SSLerr(SSL_F_SSL_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
443            ret = -1;
444#else
445            ret = 0;
446#endif
447        }
448        break;
449    case BIO_CTRL_GET_CALLBACK:
450        {
451            void (**fptr) (const SSL *xssl, int type, int val);
452
453            fptr = (void (**)(const SSL *xssl, int type, int val))ptr;
454            *fptr = SSL_get_info_callback(ssl);
455        }
456        break;
457    default:
458        ret = BIO_ctrl(ssl->rbio, cmd, num, ptr);
459        break;
460    }
461    return (ret);
462}
463
464static long ssl_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
465{
466    SSL *ssl;
467    BIO_SSL *bs;
468    long ret = 1;
469
470    bs = (BIO_SSL *)b->ptr;
471    ssl = bs->ssl;
472    switch (cmd) {
473    case BIO_CTRL_SET_CALLBACK:
474        {
475            /*
476             * FIXME: setting this via a completely different prototype seems
477             * like a crap idea
478             */
479            SSL_set_info_callback(ssl, (void (*)(const SSL *, int, int))fp);
480        }
481        break;
482    default:
483        ret = BIO_callback_ctrl(ssl->rbio, cmd, fp);
484        break;
485    }
486    return (ret);
487}
488
489static int ssl_puts(BIO *bp, const char *str)
490{
491    int n, ret;
492
493    n = strlen(str);
494    ret = BIO_write(bp, str, n);
495    return (ret);
496}
497
498BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx)
499{
500#ifndef OPENSSL_NO_SOCK
501    BIO *ret = NULL, *buf = NULL, *ssl = NULL;
502
503    if ((buf = BIO_new(BIO_f_buffer())) == NULL)
504        return (NULL);
505    if ((ssl = BIO_new_ssl_connect(ctx)) == NULL)
506        goto err;
507    if ((ret = BIO_push(buf, ssl)) == NULL)
508        goto err;
509    return (ret);
510 err:
511    if (buf != NULL)
512        BIO_free(buf);
513    if (ssl != NULL)
514        BIO_free(ssl);
515#endif
516    return (NULL);
517}
518
519BIO *BIO_new_ssl_connect(SSL_CTX *ctx)
520{
521    BIO *ret = NULL, *con = NULL, *ssl = NULL;
522
523    if ((con = BIO_new(BIO_s_connect())) == NULL)
524        return (NULL);
525    if ((ssl = BIO_new_ssl(ctx, 1)) == NULL)
526        goto err;
527    if ((ret = BIO_push(ssl, con)) == NULL)
528        goto err;
529    return (ret);
530 err:
531    if (con != NULL)
532        BIO_free(con);
533    if (ret != NULL)
534        BIO_free(ret);
535    return (NULL);
536}
537
538BIO *BIO_new_ssl(SSL_CTX *ctx, int client)
539{
540    BIO *ret;
541    SSL *ssl;
542
543    if ((ret = BIO_new(BIO_f_ssl())) == NULL)
544        return (NULL);
545    if ((ssl = SSL_new(ctx)) == NULL) {
546        BIO_free(ret);
547        return (NULL);
548    }
549    if (client)
550        SSL_set_connect_state(ssl);
551    else
552        SSL_set_accept_state(ssl);
553
554    BIO_set_ssl(ret, ssl, BIO_CLOSE);
555    return (ret);
556}
557
558int BIO_ssl_copy_session_id(BIO *t, BIO *f)
559{
560    t = BIO_find_type(t, BIO_TYPE_SSL);
561    f = BIO_find_type(f, BIO_TYPE_SSL);
562    if ((t == NULL) || (f == NULL))
563        return (0);
564    if ((((BIO_SSL *)t->ptr)->ssl == NULL) ||
565        (((BIO_SSL *)f->ptr)->ssl == NULL))
566        return (0);
567    SSL_copy_session_id(((BIO_SSL *)t->ptr)->ssl, ((BIO_SSL *)f->ptr)->ssl);
568    return (1);
569}
570
571void BIO_ssl_shutdown(BIO *b)
572{
573    SSL *s;
574
575    while (b != NULL) {
576        if (b->method->type == BIO_TYPE_SSL) {
577            s = ((BIO_SSL *)b->ptr)->ssl;
578            SSL_shutdown(s);
579            break;
580        }
581        b = b->next_bio;
582    }
583}
584