]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - crypto/openssl/ssl/ssl_lib.c
Merge OpenSSL 0.9.8zf.
[FreeBSD/stable/9.git] / crypto / openssl / ssl / ssl_lib.c
1 /*
2  * ! \file ssl/ssl_lib.c \brief Version independent SSL functions.
3  */
4 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5  * All rights reserved.
6  *
7  * This package is an SSL implementation written
8  * by Eric Young (eay@cryptsoft.com).
9  * The implementation was written so as to conform with Netscapes SSL.
10  *
11  * This library is free for commercial and non-commercial use as long as
12  * the following conditions are aheared to.  The following conditions
13  * apply to all code found in this distribution, be it the RC4, RSA,
14  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
15  * included with this distribution is covered by the same copyright terms
16  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
17  *
18  * Copyright remains Eric Young's, and as such any Copyright notices in
19  * the code are not to be removed.
20  * If this package is used in a product, Eric Young should be given attribution
21  * as the author of the parts of the library used.
22  * This can be in the form of a textual message at program startup or
23  * in documentation (online or textual) provided with the package.
24  *
25  * Redistribution and use in source and binary forms, with or without
26  * modification, are permitted provided that the following conditions
27  * are met:
28  * 1. Redistributions of source code must retain the copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. Redistributions in binary form must reproduce the above copyright
31  *    notice, this list of conditions and the following disclaimer in the
32  *    documentation and/or other materials provided with the distribution.
33  * 3. All advertising materials mentioning features or use of this software
34  *    must display the following acknowledgement:
35  *    "This product includes cryptographic software written by
36  *     Eric Young (eay@cryptsoft.com)"
37  *    The word 'cryptographic' can be left out if the rouines from the library
38  *    being used are not cryptographic related :-).
39  * 4. If you include any Windows specific code (or a derivative thereof) from
40  *    the apps directory (application code) you must include an acknowledgement:
41  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
42  *
43  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
44  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
47  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  *
55  * The licence and distribution terms for any publically available version or
56  * derivative of this code cannot be changed.  i.e. this code cannot simply be
57  * copied and put under another distribution licence
58  * [including the GNU Public Licence.]
59  */
60 /* ====================================================================
61  * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
62  *
63  * Redistribution and use in source and binary forms, with or without
64  * modification, are permitted provided that the following conditions
65  * are met:
66  *
67  * 1. Redistributions of source code must retain the above copyright
68  *    notice, this list of conditions and the following disclaimer.
69  *
70  * 2. Redistributions in binary form must reproduce the above copyright
71  *    notice, this list of conditions and the following disclaimer in
72  *    the documentation and/or other materials provided with the
73  *    distribution.
74  *
75  * 3. All advertising materials mentioning features or use of this
76  *    software must display the following acknowledgment:
77  *    "This product includes software developed by the OpenSSL Project
78  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
79  *
80  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
81  *    endorse or promote products derived from this software without
82  *    prior written permission. For written permission, please contact
83  *    openssl-core@openssl.org.
84  *
85  * 5. Products derived from this software may not be called "OpenSSL"
86  *    nor may "OpenSSL" appear in their names without prior written
87  *    permission of the OpenSSL Project.
88  *
89  * 6. Redistributions of any form whatsoever must retain the following
90  *    acknowledgment:
91  *    "This product includes software developed by the OpenSSL Project
92  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
93  *
94  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
95  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
96  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
97  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
98  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
99  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
100  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
101  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
102  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
103  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
104  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
105  * OF THE POSSIBILITY OF SUCH DAMAGE.
106  * ====================================================================
107  *
108  * This product includes cryptographic software written by Eric Young
109  * (eay@cryptsoft.com).  This product includes software written by Tim
110  * Hudson (tjh@cryptsoft.com).
111  *
112  */
113 /* ====================================================================
114  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
115  * ECC cipher suite support in OpenSSL originally developed by
116  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
117  */
118
119 #ifdef REF_CHECK
120 # include <assert.h>
121 #endif
122 #include <stdio.h>
123 #include "ssl_locl.h"
124 #include "kssl_lcl.h"
125 #include <openssl/objects.h>
126 #include <openssl/lhash.h>
127 #include <openssl/x509v3.h>
128 #include <openssl/rand.h>
129 #include <openssl/ocsp.h>
130 #ifndef OPENSSL_NO_DH
131 # include <openssl/dh.h>
132 #endif
133 #ifndef OPENSSL_NO_ENGINE
134 # include <openssl/engine.h>
135 #endif
136
137 const char *SSL_version_str = OPENSSL_VERSION_TEXT;
138
139 SSL3_ENC_METHOD ssl3_undef_enc_method = {
140     /*
141      * evil casts, but these functions are only called if there's a library
142      * bug
143      */
144     (int (*)(SSL *, int))ssl_undefined_function,
145     (int (*)(SSL *, unsigned char *, int))ssl_undefined_function,
146     ssl_undefined_function,
147     (int (*)(SSL *, unsigned char *, unsigned char *, int))
148         ssl_undefined_function,
149     (int (*)(SSL *, int))ssl_undefined_function,
150     (int (*)
151      (SSL *, EVP_MD_CTX *, EVP_MD_CTX *, const char *, int,
152       unsigned char *))ssl_undefined_function,
153     0,                          /* finish_mac_length */
154     (int (*)(SSL *, EVP_MD_CTX *, unsigned char *))ssl_undefined_function,
155     NULL,                       /* client_finished_label */
156     0,                          /* client_finished_label_len */
157     NULL,                       /* server_finished_label */
158     0,                          /* server_finished_label_len */
159     (int (*)(int))ssl_undefined_function
160 };
161
162 int SSL_clear(SSL *s)
163 {
164
165     if (s->method == NULL) {
166         SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
167         return (0);
168     }
169
170     if (ssl_clear_bad_session(s)) {
171         SSL_SESSION_free(s->session);
172         s->session = NULL;
173     }
174
175     s->error = 0;
176     s->hit = 0;
177     s->shutdown = 0;
178
179 #if 0
180     /*
181      * Disabled since version 1.10 of this file (early return not
182      * needed because SSL_clear is not called when doing renegotiation)
183      */
184     /*
185      * This is set if we are doing dynamic renegotiation so keep
186      * the old cipher.  It is sort of a SSL_clear_lite :-)
187      */
188     if (s->new_session)
189         return (1);
190 #else
191     if (s->new_session) {
192         SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
193         return 0;
194     }
195 #endif
196
197     s->type = 0;
198
199     s->state = SSL_ST_BEFORE | ((s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT);
200
201     s->version = s->method->version;
202     s->client_version = s->version;
203     s->rwstate = SSL_NOTHING;
204     s->rstate = SSL_ST_READ_HEADER;
205 #if 0
206     s->read_ahead = s->ctx->read_ahead;
207 #endif
208
209     if (s->init_buf != NULL) {
210         BUF_MEM_free(s->init_buf);
211         s->init_buf = NULL;
212     }
213
214     ssl_clear_cipher_ctx(s);
215
216     s->first_packet = 0;
217
218 #if 1
219     /*
220      * Check to see if we were changed into a different method, if so, revert
221      * back if we are not doing session-id reuse.
222      */
223     if (!s->in_handshake && (s->session == NULL)
224         && (s->method != s->ctx->method)) {
225         s->method->ssl_free(s);
226         s->method = s->ctx->method;
227         if (!s->method->ssl_new(s))
228             return (0);
229     } else
230 #endif
231         s->method->ssl_clear(s);
232     return (1);
233 }
234
235 /** Used to change an SSL_CTXs default SSL method type */
236 int SSL_CTX_set_ssl_version(SSL_CTX *ctx, SSL_METHOD *meth)
237 {
238     STACK_OF(SSL_CIPHER) *sk;
239
240     ctx->method = meth;
241
242     sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
243                                 &(ctx->cipher_list_by_id),
244                                 SSL_DEFAULT_CIPHER_LIST);
245     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
246         SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION,
247                SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
248         return (0);
249     }
250     return (1);
251 }
252
253 SSL *SSL_new(SSL_CTX *ctx)
254 {
255     SSL *s;
256
257     if (ctx == NULL) {
258         SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
259         return (NULL);
260     }
261     if (ctx->method == NULL) {
262         SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
263         return (NULL);
264     }
265
266     s = (SSL *)OPENSSL_malloc(sizeof(SSL));
267     if (s == NULL)
268         goto err;
269     memset(s, 0, sizeof(SSL));
270
271 #ifndef OPENSSL_NO_KRB5
272     s->kssl_ctx = kssl_ctx_new();
273 #endif                          /* OPENSSL_NO_KRB5 */
274
275     s->options = ctx->options;
276     s->mode = ctx->mode;
277     s->max_cert_list = ctx->max_cert_list;
278
279     if (ctx->cert != NULL) {
280         /*
281          * Earlier library versions used to copy the pointer to the CERT, not
282          * its contents; only when setting new parameters for the per-SSL
283          * copy, ssl_cert_new would be called (and the direct reference to
284          * the per-SSL_CTX settings would be lost, but those still were
285          * indirectly accessed for various purposes, and for that reason they
286          * used to be known as s->ctx->default_cert). Now we don't look at the
287          * SSL_CTX's CERT after having duplicated it once.
288          */
289
290         s->cert = ssl_cert_dup(ctx->cert);
291         if (s->cert == NULL)
292             goto err;
293     } else
294         s->cert = NULL;         /* Cannot really happen (see SSL_CTX_new) */
295
296     s->read_ahead = ctx->read_ahead;
297     s->msg_callback = ctx->msg_callback;
298     s->msg_callback_arg = ctx->msg_callback_arg;
299     s->verify_mode = ctx->verify_mode;
300 #if 0
301     s->verify_depth = ctx->verify_depth;
302 #endif
303     s->sid_ctx_length = ctx->sid_ctx_length;
304     OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx);
305     memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
306     s->verify_callback = ctx->default_verify_callback;
307     s->generate_session_id = ctx->generate_session_id;
308
309     s->param = X509_VERIFY_PARAM_new();
310     if (!s->param)
311         goto err;
312     X509_VERIFY_PARAM_inherit(s->param, ctx->param);
313 #if 0
314     s->purpose = ctx->purpose;
315     s->trust = ctx->trust;
316 #endif
317     s->quiet_shutdown = ctx->quiet_shutdown;
318
319     CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
320     s->ctx = ctx;
321 #ifndef OPENSSL_NO_TLSEXT
322     s->tlsext_debug_cb = 0;
323     s->tlsext_debug_arg = NULL;
324     s->tlsext_ticket_expected = 0;
325     s->tlsext_status_type = -1;
326     s->tlsext_status_expected = 0;
327     s->tlsext_ocsp_ids = NULL;
328     s->tlsext_ocsp_exts = NULL;
329     s->tlsext_ocsp_resp = NULL;
330     s->tlsext_ocsp_resplen = -1;
331     CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
332     s->initial_ctx = ctx;
333 #endif
334     s->verify_result = X509_V_OK;
335
336     s->method = ctx->method;
337
338     if (!s->method->ssl_new(s))
339         goto err;
340
341     s->references = 1;
342     s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
343
344     SSL_clear(s);
345
346     CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
347
348     return (s);
349  err:
350     if (s != NULL) {
351         if (s->cert != NULL)
352             ssl_cert_free(s->cert);
353         if (s->ctx != NULL)
354             SSL_CTX_free(s->ctx); /* decrement reference count */
355         OPENSSL_free(s);
356     }
357     SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
358     return (NULL);
359 }
360
361 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
362                                    unsigned int sid_ctx_len)
363 {
364     if (sid_ctx_len > sizeof ctx->sid_ctx) {
365         SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
366                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
367         return 0;
368     }
369     ctx->sid_ctx_length = sid_ctx_len;
370     memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
371
372     return 1;
373 }
374
375 int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
376                                unsigned int sid_ctx_len)
377 {
378     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
379         SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
380                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
381         return 0;
382     }
383     ssl->sid_ctx_length = sid_ctx_len;
384     memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
385
386     return 1;
387 }
388
389 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
390 {
391     CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
392     ctx->generate_session_id = cb;
393     CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
394     return 1;
395 }
396
397 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
398 {
399     CRYPTO_w_lock(CRYPTO_LOCK_SSL);
400     ssl->generate_session_id = cb;
401     CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
402     return 1;
403 }
404
405 int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
406                                 unsigned int id_len)
407 {
408     /*
409      * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
410      * we can "construct" a session to give us the desired check - ie. to
411      * find if there's a session in the hash table that would conflict with
412      * any new session built out of this id/id_len and the ssl_version in use
413      * by this SSL.
414      */
415     SSL_SESSION r, *p;
416
417     if (id_len > sizeof r.session_id)
418         return 0;
419
420     r.ssl_version = ssl->version;
421     r.session_id_length = id_len;
422     memcpy(r.session_id, id, id_len);
423     /*
424      * NB: SSLv2 always uses a fixed 16-byte session ID, so even if a
425      * callback is calling us to check the uniqueness of a shorter ID, it
426      * must be compared as a padded-out ID because that is what it will be
427      * converted to when the callback has finished choosing it.
428      */
429     if ((r.ssl_version == SSL2_VERSION) &&
430         (id_len < SSL2_SSL_SESSION_ID_LENGTH)) {
431         memset(r.session_id + id_len, 0, SSL2_SSL_SESSION_ID_LENGTH - id_len);
432         r.session_id_length = SSL2_SSL_SESSION_ID_LENGTH;
433     }
434
435     CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
436     p = (SSL_SESSION *)lh_retrieve(ssl->ctx->sessions, &r);
437     CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
438     return (p != NULL);
439 }
440
441 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
442 {
443     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
444 }
445
446 int SSL_set_purpose(SSL *s, int purpose)
447 {
448     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
449 }
450
451 int SSL_CTX_set_trust(SSL_CTX *s, int trust)
452 {
453     return X509_VERIFY_PARAM_set_trust(s->param, trust);
454 }
455
456 int SSL_set_trust(SSL *s, int trust)
457 {
458     return X509_VERIFY_PARAM_set_trust(s->param, trust);
459 }
460
461 void SSL_free(SSL *s)
462 {
463     int i;
464
465     if (s == NULL)
466         return;
467
468     i = CRYPTO_add(&s->references, -1, CRYPTO_LOCK_SSL);
469 #ifdef REF_PRINT
470     REF_PRINT("SSL", s);
471 #endif
472     if (i > 0)
473         return;
474 #ifdef REF_CHECK
475     if (i < 0) {
476         fprintf(stderr, "SSL_free, bad reference count\n");
477         abort();                /* ok */
478     }
479 #endif
480
481     if (s->param)
482         X509_VERIFY_PARAM_free(s->param);
483
484     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
485
486     if (s->bbio != NULL) {
487         /* If the buffering BIO is in place, pop it off */
488         if (s->bbio == s->wbio) {
489             s->wbio = BIO_pop(s->wbio);
490         }
491         BIO_free(s->bbio);
492         s->bbio = NULL;
493     }
494     if (s->rbio != NULL)
495         BIO_free_all(s->rbio);
496     if ((s->wbio != NULL) && (s->wbio != s->rbio))
497         BIO_free_all(s->wbio);
498
499     if (s->init_buf != NULL)
500         BUF_MEM_free(s->init_buf);
501
502     /* add extra stuff */
503     if (s->cipher_list != NULL)
504         sk_SSL_CIPHER_free(s->cipher_list);
505     if (s->cipher_list_by_id != NULL)
506         sk_SSL_CIPHER_free(s->cipher_list_by_id);
507
508     /* Make the next call work :-) */
509     if (s->session != NULL) {
510         ssl_clear_bad_session(s);
511         SSL_SESSION_free(s->session);
512     }
513
514     ssl_clear_cipher_ctx(s);
515
516     if (s->cert != NULL)
517         ssl_cert_free(s->cert);
518     /* Free up if allocated */
519
520 #ifndef OPENSSL_NO_TLSEXT
521     if (s->tlsext_hostname)
522         OPENSSL_free(s->tlsext_hostname);
523     if (s->initial_ctx)
524         SSL_CTX_free(s->initial_ctx);
525     if (s->tlsext_ocsp_exts)
526         sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free);
527     if (s->tlsext_ocsp_ids)
528         sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free);
529     if (s->tlsext_ocsp_resp)
530         OPENSSL_free(s->tlsext_ocsp_resp);
531 #endif
532     if (s->client_CA != NULL)
533         sk_X509_NAME_pop_free(s->client_CA, X509_NAME_free);
534
535     if (s->method != NULL)
536         s->method->ssl_free(s);
537
538     if (s->ctx)
539         SSL_CTX_free(s->ctx);
540
541 #ifndef OPENSSL_NO_KRB5
542     if (s->kssl_ctx != NULL)
543         kssl_ctx_free(s->kssl_ctx);
544 #endif                          /* OPENSSL_NO_KRB5 */
545
546     OPENSSL_free(s);
547 }
548
549 void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
550 {
551     /*
552      * If the output buffering BIO is still in place, remove it
553      */
554     if (s->bbio != NULL) {
555         if (s->wbio == s->bbio) {
556             s->wbio = s->wbio->next_bio;
557             s->bbio->next_bio = NULL;
558         }
559     }
560     if ((s->rbio != NULL) && (s->rbio != rbio))
561         BIO_free_all(s->rbio);
562     if ((s->wbio != NULL) && (s->wbio != wbio) && (s->rbio != s->wbio))
563         BIO_free_all(s->wbio);
564     s->rbio = rbio;
565     s->wbio = wbio;
566 }
567
568 BIO *SSL_get_rbio(const SSL *s)
569 {
570     return (s->rbio);
571 }
572
573 BIO *SSL_get_wbio(const SSL *s)
574 {
575     return (s->wbio);
576 }
577
578 int SSL_get_fd(const SSL *s)
579 {
580     return (SSL_get_rfd(s));
581 }
582
583 int SSL_get_rfd(const SSL *s)
584 {
585     int ret = -1;
586     BIO *b, *r;
587
588     b = SSL_get_rbio(s);
589     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
590     if (r != NULL)
591         BIO_get_fd(r, &ret);
592     return (ret);
593 }
594
595 int SSL_get_wfd(const SSL *s)
596 {
597     int ret = -1;
598     BIO *b, *r;
599
600     b = SSL_get_wbio(s);
601     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
602     if (r != NULL)
603         BIO_get_fd(r, &ret);
604     return (ret);
605 }
606
607 #ifndef OPENSSL_NO_SOCK
608 int SSL_set_fd(SSL *s, int fd)
609 {
610     int ret = 0;
611     BIO *bio = NULL;
612
613     bio = BIO_new(BIO_s_socket());
614
615     if (bio == NULL) {
616         SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
617         goto err;
618     }
619     BIO_set_fd(bio, fd, BIO_NOCLOSE);
620     SSL_set_bio(s, bio, bio);
621     ret = 1;
622  err:
623     return (ret);
624 }
625
626 int SSL_set_wfd(SSL *s, int fd)
627 {
628     int ret = 0;
629     BIO *bio = NULL;
630
631     if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET)
632         || ((int)BIO_get_fd(s->rbio, NULL) != fd)) {
633         bio = BIO_new(BIO_s_socket());
634
635         if (bio == NULL) {
636             SSLerr(SSL_F_SSL_SET_WFD, ERR_R_BUF_LIB);
637             goto err;
638         }
639         BIO_set_fd(bio, fd, BIO_NOCLOSE);
640         SSL_set_bio(s, SSL_get_rbio(s), bio);
641     } else
642         SSL_set_bio(s, SSL_get_rbio(s), SSL_get_rbio(s));
643     ret = 1;
644  err:
645     return (ret);
646 }
647
648 int SSL_set_rfd(SSL *s, int fd)
649 {
650     int ret = 0;
651     BIO *bio = NULL;
652
653     if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET)
654         || ((int)BIO_get_fd(s->wbio, NULL) != fd)) {
655         bio = BIO_new(BIO_s_socket());
656
657         if (bio == NULL) {
658             SSLerr(SSL_F_SSL_SET_RFD, ERR_R_BUF_LIB);
659             goto err;
660         }
661         BIO_set_fd(bio, fd, BIO_NOCLOSE);
662         SSL_set_bio(s, bio, SSL_get_wbio(s));
663     } else
664         SSL_set_bio(s, SSL_get_wbio(s), SSL_get_wbio(s));
665     ret = 1;
666  err:
667     return (ret);
668 }
669 #endif
670
671 /* return length of latest Finished message we sent, copy to 'buf' */
672 size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
673 {
674     size_t ret = 0;
675
676     if (s->s3 != NULL) {
677         ret = s->s3->tmp.finish_md_len;
678         if (count > ret)
679             count = ret;
680         memcpy(buf, s->s3->tmp.finish_md, count);
681     }
682     return ret;
683 }
684
685 /* return length of latest Finished message we expected, copy to 'buf' */
686 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
687 {
688     size_t ret = 0;
689
690     if (s->s3 != NULL) {
691         ret = s->s3->tmp.peer_finish_md_len;
692         if (count > ret)
693             count = ret;
694         memcpy(buf, s->s3->tmp.peer_finish_md, count);
695     }
696     return ret;
697 }
698
699 int SSL_get_verify_mode(const SSL *s)
700 {
701     return (s->verify_mode);
702 }
703
704 int SSL_get_verify_depth(const SSL *s)
705 {
706     return X509_VERIFY_PARAM_get_depth(s->param);
707 }
708
709 int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *) {
710     return (s->verify_callback);
711 }
712
713 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
714 {
715     return (ctx->verify_mode);
716 }
717
718 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
719 {
720     return X509_VERIFY_PARAM_get_depth(ctx->param);
721 }
722
723 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int, X509_STORE_CTX *) {
724     return (ctx->default_verify_callback);
725 }
726
727 void SSL_set_verify(SSL *s, int mode,
728                     int (*callback) (int ok, X509_STORE_CTX *ctx))
729 {
730     s->verify_mode = mode;
731     if (callback != NULL)
732         s->verify_callback = callback;
733 }
734
735 void SSL_set_verify_depth(SSL *s, int depth)
736 {
737     X509_VERIFY_PARAM_set_depth(s->param, depth);
738 }
739
740 void SSL_set_read_ahead(SSL *s, int yes)
741 {
742     s->read_ahead = yes;
743 }
744
745 int SSL_get_read_ahead(const SSL *s)
746 {
747     return (s->read_ahead);
748 }
749
750 int SSL_pending(const SSL *s)
751 {
752     /*
753      * SSL_pending cannot work properly if read-ahead is enabled
754      * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
755      * impossible to fix since SSL_pending cannot report errors that may be
756      * observed while scanning the new data. (Note that SSL_pending() is
757      * often used as a boolean value, so we'd better not return -1.)
758      */
759     return (s->method->ssl_pending(s));
760 }
761
762 X509 *SSL_get_peer_certificate(const SSL *s)
763 {
764     X509 *r;
765
766     if ((s == NULL) || (s->session == NULL))
767         r = NULL;
768     else
769         r = s->session->peer;
770
771     if (r == NULL)
772         return (r);
773
774     CRYPTO_add(&r->references, 1, CRYPTO_LOCK_X509);
775
776     return (r);
777 }
778
779 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
780 {
781     STACK_OF(X509) *r;
782
783     if ((s == NULL) || (s->session == NULL)
784         || (s->session->sess_cert == NULL))
785         r = NULL;
786     else
787         r = s->session->sess_cert->cert_chain;
788
789     /*
790      * If we are a client, cert_chain includes the peer's own certificate; if
791      * we are a server, it does not.
792      */
793
794     return (r);
795 }
796
797 /*
798  * Now in theory, since the calling process own 't' it should be safe to
799  * modify.  We need to be able to read f without being hassled
800  */
801 void SSL_copy_session_id(SSL *t, const SSL *f)
802 {
803     CERT *tmp;
804
805     /* Do we need to to SSL locking? */
806     SSL_set_session(t, SSL_get_session(f));
807
808     /*
809      * what if we are setup as SSLv2 but want to talk SSLv3 or vice-versa
810      */
811     if (t->method != f->method) {
812         t->method->ssl_free(t); /* cleanup current */
813         t->method = f->method;  /* change method */
814         t->method->ssl_new(t);  /* setup new */
815     }
816
817     tmp = t->cert;
818     if (f->cert != NULL) {
819         CRYPTO_add(&f->cert->references, 1, CRYPTO_LOCK_SSL_CERT);
820         t->cert = f->cert;
821     } else
822         t->cert = NULL;
823     if (tmp != NULL)
824         ssl_cert_free(tmp);
825     SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length);
826 }
827
828 /* Fix this so it checks all the valid key/cert options */
829 int SSL_CTX_check_private_key(const SSL_CTX *ctx)
830 {
831     if ((ctx == NULL) ||
832         (ctx->cert == NULL) || (ctx->cert->key->x509 == NULL)) {
833         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
834                SSL_R_NO_CERTIFICATE_ASSIGNED);
835         return (0);
836     }
837     if (ctx->cert->key->privatekey == NULL) {
838         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
839                SSL_R_NO_PRIVATE_KEY_ASSIGNED);
840         return (0);
841     }
842     return (X509_check_private_key
843             (ctx->cert->key->x509, ctx->cert->key->privatekey));
844 }
845
846 /* Fix this function so that it takes an optional type parameter */
847 int SSL_check_private_key(const SSL *ssl)
848 {
849     if (ssl == NULL) {
850         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
851         return (0);
852     }
853     if (ssl->cert == NULL) {
854         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
855         return 0;
856     }
857     if (ssl->cert->key->x509 == NULL) {
858         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
859         return (0);
860     }
861     if (ssl->cert->key->privatekey == NULL) {
862         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
863         return (0);
864     }
865     return (X509_check_private_key(ssl->cert->key->x509,
866                                    ssl->cert->key->privatekey));
867 }
868
869 int SSL_accept(SSL *s)
870 {
871     if (s->handshake_func == 0)
872         /* Not properly initialized yet */
873         SSL_set_accept_state(s);
874
875     return (s->method->ssl_accept(s));
876 }
877
878 int SSL_connect(SSL *s)
879 {
880     if (s->handshake_func == 0)
881         /* Not properly initialized yet */
882         SSL_set_connect_state(s);
883
884     return (s->method->ssl_connect(s));
885 }
886
887 long SSL_get_default_timeout(const SSL *s)
888 {
889     return (s->method->get_timeout());
890 }
891
892 int SSL_read(SSL *s, void *buf, int num)
893 {
894     if (s->handshake_func == 0) {
895         SSLerr(SSL_F_SSL_READ, SSL_R_UNINITIALIZED);
896         return -1;
897     }
898
899     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
900         s->rwstate = SSL_NOTHING;
901         return (0);
902     }
903     return (s->method->ssl_read(s, buf, num));
904 }
905
906 int SSL_peek(SSL *s, void *buf, int num)
907 {
908     if (s->handshake_func == 0) {
909         SSLerr(SSL_F_SSL_PEEK, SSL_R_UNINITIALIZED);
910         return -1;
911     }
912
913     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
914         return (0);
915     }
916     return (s->method->ssl_peek(s, buf, num));
917 }
918
919 int SSL_write(SSL *s, const void *buf, int num)
920 {
921     if (s->handshake_func == 0) {
922         SSLerr(SSL_F_SSL_WRITE, SSL_R_UNINITIALIZED);
923         return -1;
924     }
925
926     if (s->shutdown & SSL_SENT_SHUTDOWN) {
927         s->rwstate = SSL_NOTHING;
928         SSLerr(SSL_F_SSL_WRITE, SSL_R_PROTOCOL_IS_SHUTDOWN);
929         return (-1);
930     }
931     return (s->method->ssl_write(s, buf, num));
932 }
933
934 int SSL_shutdown(SSL *s)
935 {
936     /*
937      * Note that this function behaves differently from what one might
938      * expect.  Return values are 0 for no success (yet), 1 for success; but
939      * calling it once is usually not enough, even if blocking I/O is used
940      * (see ssl3_shutdown).
941      */
942
943     if (s->handshake_func == 0) {
944         SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED);
945         return -1;
946     }
947
948     if ((s != NULL) && !SSL_in_init(s))
949         return (s->method->ssl_shutdown(s));
950     else
951         return (1);
952 }
953
954 int SSL_renegotiate(SSL *s)
955 {
956     if (s->new_session == 0) {
957         s->new_session = 1;
958     }
959     return (s->method->ssl_renegotiate(s));
960 }
961
962 int SSL_renegotiate_pending(SSL *s)
963 {
964     /*
965      * becomes true when negotiation is requested; false again once a
966      * handshake has finished
967      */
968     return (s->new_session != 0);
969 }
970
971 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
972 {
973     long l;
974
975     switch (cmd) {
976     case SSL_CTRL_GET_READ_AHEAD:
977         return (s->read_ahead);
978     case SSL_CTRL_SET_READ_AHEAD:
979         l = s->read_ahead;
980         s->read_ahead = larg;
981         return (l);
982
983     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
984         s->msg_callback_arg = parg;
985         return 1;
986
987     case SSL_CTRL_OPTIONS:
988         return (s->options |= larg);
989     case SSL_CTRL_CLEAR_OPTIONS:
990         return (s->options &= ~larg);
991     case SSL_CTRL_MODE:
992         return (s->mode |= larg);
993     case SSL_CTRL_CLEAR_MODE:
994         return (s->mode &= ~larg);
995     case SSL_CTRL_GET_MAX_CERT_LIST:
996         return (s->max_cert_list);
997     case SSL_CTRL_SET_MAX_CERT_LIST:
998         l = s->max_cert_list;
999         s->max_cert_list = larg;
1000         return (l);
1001     case SSL_CTRL_SET_MTU:
1002 #ifndef OPENSSL_NO_DTLS1
1003         if (larg < (long)dtls1_min_mtu())
1004             return 0;
1005 #endif
1006
1007         if (SSL_version(s) == DTLS1_VERSION ||
1008             SSL_version(s) == DTLS1_BAD_VER) {
1009             s->d1->mtu = larg;
1010             return larg;
1011         }
1012         return 0;
1013     case SSL_CTRL_GET_RI_SUPPORT:
1014         if (s->s3)
1015             return s->s3->send_connection_binding;
1016         else
1017             return 0;
1018     default:
1019         return (s->method->ssl_ctrl(s, cmd, larg, parg));
1020     }
1021 }
1022
1023 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
1024 {
1025     switch (cmd) {
1026     case SSL_CTRL_SET_MSG_CALLBACK:
1027         s->msg_callback = (void (*)
1028                            (int write_p, int version, int content_type,
1029                             const void *buf, size_t len, SSL *ssl,
1030                             void *arg))(fp);
1031         return 1;
1032
1033     default:
1034         return (s->method->ssl_callback_ctrl(s, cmd, fp));
1035     }
1036 }
1037
1038 struct lhash_st *SSL_CTX_sessions(SSL_CTX *ctx)
1039 {
1040     return ctx->sessions;
1041 }
1042
1043 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
1044 {
1045     long l;
1046
1047     switch (cmd) {
1048     case SSL_CTRL_GET_READ_AHEAD:
1049         return (ctx->read_ahead);
1050     case SSL_CTRL_SET_READ_AHEAD:
1051         l = ctx->read_ahead;
1052         ctx->read_ahead = larg;
1053         return (l);
1054
1055     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1056         ctx->msg_callback_arg = parg;
1057         return 1;
1058
1059     case SSL_CTRL_GET_MAX_CERT_LIST:
1060         return (ctx->max_cert_list);
1061     case SSL_CTRL_SET_MAX_CERT_LIST:
1062         l = ctx->max_cert_list;
1063         ctx->max_cert_list = larg;
1064         return (l);
1065
1066     case SSL_CTRL_SET_SESS_CACHE_SIZE:
1067         l = ctx->session_cache_size;
1068         ctx->session_cache_size = larg;
1069         return (l);
1070     case SSL_CTRL_GET_SESS_CACHE_SIZE:
1071         return (ctx->session_cache_size);
1072     case SSL_CTRL_SET_SESS_CACHE_MODE:
1073         l = ctx->session_cache_mode;
1074         ctx->session_cache_mode = larg;
1075         return (l);
1076     case SSL_CTRL_GET_SESS_CACHE_MODE:
1077         return (ctx->session_cache_mode);
1078
1079     case SSL_CTRL_SESS_NUMBER:
1080         return (ctx->sessions->num_items);
1081     case SSL_CTRL_SESS_CONNECT:
1082         return (ctx->stats.sess_connect);
1083     case SSL_CTRL_SESS_CONNECT_GOOD:
1084         return (ctx->stats.sess_connect_good);
1085     case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
1086         return (ctx->stats.sess_connect_renegotiate);
1087     case SSL_CTRL_SESS_ACCEPT:
1088         return (ctx->stats.sess_accept);
1089     case SSL_CTRL_SESS_ACCEPT_GOOD:
1090         return (ctx->stats.sess_accept_good);
1091     case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
1092         return (ctx->stats.sess_accept_renegotiate);
1093     case SSL_CTRL_SESS_HIT:
1094         return (ctx->stats.sess_hit);
1095     case SSL_CTRL_SESS_CB_HIT:
1096         return (ctx->stats.sess_cb_hit);
1097     case SSL_CTRL_SESS_MISSES:
1098         return (ctx->stats.sess_miss);
1099     case SSL_CTRL_SESS_TIMEOUTS:
1100         return (ctx->stats.sess_timeout);
1101     case SSL_CTRL_SESS_CACHE_FULL:
1102         return (ctx->stats.sess_cache_full);
1103     case SSL_CTRL_OPTIONS:
1104         return (ctx->options |= larg);
1105     case SSL_CTRL_CLEAR_OPTIONS:
1106         return (ctx->options &= ~larg);
1107     case SSL_CTRL_MODE:
1108         return (ctx->mode |= larg);
1109     case SSL_CTRL_CLEAR_MODE:
1110         return (ctx->mode &= ~larg);
1111     default:
1112         return (ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg));
1113     }
1114 }
1115
1116 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
1117 {
1118     switch (cmd) {
1119     case SSL_CTRL_SET_MSG_CALLBACK:
1120         ctx->msg_callback = (void (*)
1121                              (int write_p, int version, int content_type,
1122                               const void *buf, size_t len, SSL *ssl,
1123                               void *arg))(fp);
1124         return 1;
1125
1126     default:
1127         return (ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp));
1128     }
1129 }
1130
1131 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
1132 {
1133     long l;
1134
1135     l = a->id - b->id;
1136     if (l == 0L)
1137         return (0);
1138     else
1139         return ((l > 0) ? 1 : -1);
1140 }
1141
1142 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
1143                           const SSL_CIPHER *const *bp)
1144 {
1145     long l;
1146
1147     l = (*ap)->id - (*bp)->id;
1148     if (l == 0L)
1149         return (0);
1150     else
1151         return ((l > 0) ? 1 : -1);
1152 }
1153
1154 /** return a STACK of the ciphers available for the SSL and in order of
1155  * preference */
1156 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
1157 {
1158     if (s != NULL) {
1159         if (s->cipher_list != NULL) {
1160             return (s->cipher_list);
1161         } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
1162             return (s->ctx->cipher_list);
1163         }
1164     }
1165     return (NULL);
1166 }
1167
1168 /** return a STACK of the ciphers available for the SSL and in order of
1169  * algorithm id */
1170 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
1171 {
1172     if (s != NULL) {
1173         if (s->cipher_list_by_id != NULL) {
1174             return (s->cipher_list_by_id);
1175         } else if ((s->ctx != NULL) && (s->ctx->cipher_list_by_id != NULL)) {
1176             return (s->ctx->cipher_list_by_id);
1177         }
1178     }
1179     return (NULL);
1180 }
1181
1182 /** The old interface to get the same thing as SSL_get_ciphers() */
1183 const char *SSL_get_cipher_list(const SSL *s, int n)
1184 {
1185     SSL_CIPHER *c;
1186     STACK_OF(SSL_CIPHER) *sk;
1187
1188     if (s == NULL)
1189         return (NULL);
1190     sk = SSL_get_ciphers(s);
1191     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
1192         return (NULL);
1193     c = sk_SSL_CIPHER_value(sk, n);
1194     if (c == NULL)
1195         return (NULL);
1196     return (c->name);
1197 }
1198
1199 /** specify the ciphers to be used by default by the SSL_CTX */
1200 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
1201 {
1202     STACK_OF(SSL_CIPHER) *sk;
1203
1204     sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
1205                                 &ctx->cipher_list_by_id, str);
1206     /*
1207      * ssl_create_cipher_list may return an empty stack if it was unable to
1208      * find a cipher matching the given rule string (for example if the rule
1209      * string specifies a cipher which has been disabled). This is not an
1210      * error as far as ssl_create_cipher_list is concerned, and hence
1211      * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
1212      */
1213     if (sk == NULL)
1214         return 0;
1215     else if (sk_SSL_CIPHER_num(sk) == 0) {
1216         SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
1217         return 0;
1218     }
1219     return 1;
1220 }
1221
1222 /** specify the ciphers to be used by the SSL */
1223 int SSL_set_cipher_list(SSL *s, const char *str)
1224 {
1225     STACK_OF(SSL_CIPHER) *sk;
1226
1227     sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
1228                                 &s->cipher_list_by_id, str);
1229     /* see comment in SSL_CTX_set_cipher_list */
1230     if (sk == NULL)
1231         return 0;
1232     else if (sk_SSL_CIPHER_num(sk) == 0) {
1233         SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
1234         return 0;
1235     }
1236     return 1;
1237 }
1238
1239 /* works well for SSLv2, not so good for SSLv3 */
1240 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
1241 {
1242     char *p;
1243     STACK_OF(SSL_CIPHER) *sk;
1244     SSL_CIPHER *c;
1245     int i;
1246
1247     if ((s->session == NULL) || (s->session->ciphers == NULL) || (len < 2))
1248         return (NULL);
1249
1250     p = buf;
1251     sk = s->session->ciphers;
1252
1253     if (sk_SSL_CIPHER_num(sk) == 0)
1254         return NULL;
1255
1256     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1257         int n;
1258
1259         c = sk_SSL_CIPHER_value(sk, i);
1260         n = strlen(c->name);
1261         if (n + 1 > len) {
1262             if (p != buf)
1263                 --p;
1264             *p = '\0';
1265             return buf;
1266         }
1267         strcpy(p, c->name);
1268         p += n;
1269         *(p++) = ':';
1270         len -= n + 1;
1271     }
1272     p[-1] = '\0';
1273     return (buf);
1274 }
1275
1276 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
1277                              unsigned char *p,
1278                              int (*put_cb) (const SSL_CIPHER *,
1279                                             unsigned char *))
1280 {
1281     int i, j = 0;
1282     SSL_CIPHER *c;
1283     unsigned char *q;
1284 #ifndef OPENSSL_NO_KRB5
1285     int nokrb5 = !kssl_tgt_is_available(s->kssl_ctx);
1286 #endif                          /* OPENSSL_NO_KRB5 */
1287
1288     if (sk == NULL)
1289         return (0);
1290     q = p;
1291     if (put_cb == NULL)
1292         put_cb = s->method->put_cipher_by_char;
1293
1294     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1295         c = sk_SSL_CIPHER_value(sk, i);
1296 #ifndef OPENSSL_NO_KRB5
1297         if ((c->algorithms & SSL_KRB5) && nokrb5)
1298             continue;
1299 #endif                          /* OPENSSL_NO_KRB5 */
1300
1301         j = put_cb(c, p);
1302         p += j;
1303     }
1304     /*
1305      * If p == q, no ciphers; caller indicates an error. Otherwise, add
1306      * applicable SCSVs.
1307      */
1308     if (p != q) {
1309         if (!s->new_session) {
1310             static SSL_CIPHER scsv = {
1311                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0,
1312             };
1313             j = put_cb(&scsv, p);
1314             p += j;
1315 #ifdef OPENSSL_RI_DEBUG
1316             fprintf(stderr,
1317                     "TLS_EMPTY_RENEGOTIATION_INFO_SCSV sent by client\n");
1318 #endif
1319         }
1320
1321         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
1322             static SSL_CIPHER scsv = {
1323                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0,
1324             };
1325             j = put_cb(&scsv, p);
1326             p += j;
1327         }
1328     }
1329
1330     return (p - q);
1331 }
1332
1333 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, unsigned char *p,
1334                                                int num,
1335                                                STACK_OF(SSL_CIPHER) **skp)
1336 {
1337     SSL_CIPHER *c;
1338     STACK_OF(SSL_CIPHER) *sk;
1339     int i, n;
1340
1341     if (s->s3)
1342         s->s3->send_connection_binding = 0;
1343
1344     n = ssl_put_cipher_by_char(s, NULL, NULL);
1345     if (n == 0 || (num % n) != 0) {
1346         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
1347                SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
1348         return (NULL);
1349     }
1350     if ((skp == NULL) || (*skp == NULL))
1351         sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
1352     else {
1353         sk = *skp;
1354         sk_SSL_CIPHER_zero(sk);
1355     }
1356
1357     for (i = 0; i < num; i += n) {
1358         /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
1359         if (s->s3 && (n != 3 || !p[0]) &&
1360             (p[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
1361             (p[n - 1] == (SSL3_CK_SCSV & 0xff))) {
1362             /* SCSV fatal if renegotiating */
1363             if (s->new_session) {
1364                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
1365                        SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1366                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1367                 goto err;
1368             }
1369             s->s3->send_connection_binding = 1;
1370             p += n;
1371 #ifdef OPENSSL_RI_DEBUG
1372             fprintf(stderr, "SCSV received by server\n");
1373 #endif
1374             continue;
1375         }
1376
1377         /* Check for TLS_FALLBACK_SCSV */
1378         if ((n != 3 || !p[0]) &&
1379             (p[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
1380             (p[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
1381             /*
1382              * The SCSV indicates that the client previously tried a higher
1383              * version. Fail if the current version is an unexpected
1384              * downgrade.
1385              */
1386             if (!SSL_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, 0, NULL)) {
1387                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
1388                        SSL_R_INAPPROPRIATE_FALLBACK);
1389                 if (s->s3)
1390                     ssl3_send_alert(s, SSL3_AL_FATAL,
1391                                     SSL_AD_INAPPROPRIATE_FALLBACK);
1392                 goto err;
1393             }
1394             p += n;
1395             continue;
1396         }
1397
1398         c = ssl_get_cipher_by_char(s, p);
1399         p += n;
1400         if (c != NULL) {
1401             if (!sk_SSL_CIPHER_push(sk, c)) {
1402                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
1403                 goto err;
1404             }
1405         }
1406     }
1407
1408     if (skp != NULL)
1409         *skp = sk;
1410     return (sk);
1411  err:
1412     if ((skp == NULL) || (*skp == NULL))
1413         sk_SSL_CIPHER_free(sk);
1414     return (NULL);
1415 }
1416
1417 #ifndef OPENSSL_NO_TLSEXT
1418 /** return a servername extension value if provided in Client Hello, or NULL.
1419  * So far, only host_name types are defined (RFC 3546).
1420  */
1421
1422 const char *SSL_get_servername(const SSL *s, const int type)
1423 {
1424     if (type != TLSEXT_NAMETYPE_host_name)
1425         return NULL;
1426
1427     return s->session && !s->tlsext_hostname ?
1428         s->session->tlsext_hostname : s->tlsext_hostname;
1429 }
1430
1431 int SSL_get_servername_type(const SSL *s)
1432 {
1433     if (s->session
1434         && (!s->tlsext_hostname ? s->session->
1435             tlsext_hostname : s->tlsext_hostname))
1436         return TLSEXT_NAMETYPE_host_name;
1437     return -1;
1438 }
1439 #endif
1440
1441 unsigned long SSL_SESSION_hash(const SSL_SESSION *a)
1442 {
1443     unsigned long l;
1444
1445     l = (unsigned long)
1446         ((unsigned int)a->session_id[0]) |
1447         ((unsigned int)a->session_id[1] << 8L) |
1448         ((unsigned long)a->session_id[2] << 16L) |
1449         ((unsigned long)a->session_id[3] << 24L);
1450     return (l);
1451 }
1452
1453 /*
1454  * NB: If this function (or indeed the hash function which uses a sort of
1455  * coarser function than this one) is changed, ensure
1456  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
1457  * being able to construct an SSL_SESSION that will collide with any existing
1458  * session with a matching session ID.
1459  */
1460 int SSL_SESSION_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
1461 {
1462     if (a->ssl_version != b->ssl_version)
1463         return (1);
1464     if (a->session_id_length != b->session_id_length)
1465         return (1);
1466     return (memcmp(a->session_id, b->session_id, a->session_id_length));
1467 }
1468
1469 /*
1470  * These wrapper functions should remain rather than redeclaring
1471  * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
1472  * variable. The reason is that the functions aren't static, they're exposed
1473  * via ssl.h.
1474  */
1475 static IMPLEMENT_LHASH_HASH_FN(SSL_SESSION_hash, SSL_SESSION *)
1476 static IMPLEMENT_LHASH_COMP_FN(SSL_SESSION_cmp, SSL_SESSION *)
1477
1478 SSL_CTX *SSL_CTX_new(SSL_METHOD *meth)
1479 {
1480     SSL_CTX *ret = NULL;
1481
1482     if (meth == NULL) {
1483         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_NULL_SSL_METHOD_PASSED);
1484         return (NULL);
1485     }
1486 #ifdef OPENSSL_FIPS
1487     if (FIPS_mode() && (meth->version < TLS1_VERSION)) {
1488         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
1489         return NULL;
1490     }
1491 #endif
1492
1493     if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
1494         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
1495         goto err;
1496     }
1497     ret = (SSL_CTX *)OPENSSL_malloc(sizeof(SSL_CTX));
1498     if (ret == NULL)
1499         goto err;
1500
1501     memset(ret, 0, sizeof(SSL_CTX));
1502
1503     ret->method = meth;
1504
1505     ret->cert_store = NULL;
1506     ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
1507     ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
1508     ret->session_cache_head = NULL;
1509     ret->session_cache_tail = NULL;
1510
1511     /* We take the system default */
1512     ret->session_timeout = meth->get_timeout();
1513
1514     ret->new_session_cb = 0;
1515     ret->remove_session_cb = 0;
1516     ret->get_session_cb = 0;
1517     ret->generate_session_id = 0;
1518
1519     memset((char *)&ret->stats, 0, sizeof(ret->stats));
1520
1521     ret->references = 1;
1522     ret->quiet_shutdown = 0;
1523
1524 /*  ret->cipher=NULL;*/
1525 /*-
1526     ret->s2->challenge=NULL;
1527     ret->master_key=NULL;
1528     ret->key_arg=NULL;
1529     ret->s2->conn_id=NULL; */
1530
1531     ret->info_callback = NULL;
1532
1533     ret->app_verify_callback = 0;
1534     ret->app_verify_arg = NULL;
1535
1536     ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
1537     ret->read_ahead = 0;
1538     ret->msg_callback = 0;
1539     ret->msg_callback_arg = NULL;
1540     ret->verify_mode = SSL_VERIFY_NONE;
1541 #if 0
1542     ret->verify_depth = -1;     /* Don't impose a limit (but x509_lu.c does) */
1543 #endif
1544     ret->sid_ctx_length = 0;
1545     ret->default_verify_callback = NULL;
1546     if ((ret->cert = ssl_cert_new()) == NULL)
1547         goto err;
1548
1549     ret->default_passwd_callback = 0;
1550     ret->default_passwd_callback_userdata = NULL;
1551     ret->client_cert_cb = 0;
1552     ret->app_gen_cookie_cb = 0;
1553     ret->app_verify_cookie_cb = 0;
1554
1555     ret->sessions = lh_new(LHASH_HASH_FN(SSL_SESSION_hash),
1556                            LHASH_COMP_FN(SSL_SESSION_cmp));
1557     if (ret->sessions == NULL)
1558         goto err;
1559     ret->cert_store = X509_STORE_new();
1560     if (ret->cert_store == NULL)
1561         goto err;
1562
1563     ssl_create_cipher_list(ret->method,
1564                            &ret->cipher_list, &ret->cipher_list_by_id,
1565                            meth->version == SSL2_VERSION ? "SSLv2" :
1566                            SSL_DEFAULT_CIPHER_LIST);
1567     if (ret->cipher_list == NULL || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
1568         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_LIBRARY_HAS_NO_CIPHERS);
1569         goto err2;
1570     }
1571
1572     ret->param = X509_VERIFY_PARAM_new();
1573     if (!ret->param)
1574         goto err;
1575
1576     if ((ret->rsa_md5 = EVP_get_digestbyname("ssl2-md5")) == NULL) {
1577         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL2_MD5_ROUTINES);
1578         goto err2;
1579     }
1580     if ((ret->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
1581         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
1582         goto err2;
1583     }
1584     if ((ret->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
1585         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
1586         goto err2;
1587     }
1588
1589     if ((ret->client_CA = sk_X509_NAME_new_null()) == NULL)
1590         goto err;
1591
1592     CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data);
1593
1594     ret->extra_certs = NULL;
1595     /* No compression for DTLS */
1596     if (meth->version != DTLS1_VERSION)
1597         ret->comp_methods = SSL_COMP_get_compression_methods();
1598
1599 #ifndef OPENSSL_NO_TLSEXT
1600     ret->tlsext_servername_callback = 0;
1601     ret->tlsext_servername_arg = NULL;
1602     /* Setup RFC4507 ticket keys */
1603     if ((RAND_pseudo_bytes(ret->tlsext_tick_key_name, 16) <= 0)
1604         || (RAND_bytes(ret->tlsext_tick_hmac_key, 16) <= 0)
1605         || (RAND_bytes(ret->tlsext_tick_aes_key, 16) <= 0))
1606         ret->options |= SSL_OP_NO_TICKET;
1607
1608     ret->tlsext_status_cb = 0;
1609     ret->tlsext_status_arg = NULL;
1610
1611 #endif
1612
1613 #ifndef OPENSSL_NO_ENGINE
1614     ret->client_cert_engine = NULL;
1615 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
1616 #  define eng_strx(x)     #x
1617 #  define eng_str(x)      eng_strx(x)
1618     /* Use specific client engine automatically... ignore errors */
1619     {
1620         ENGINE *eng;
1621         eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1622         if (!eng) {
1623             ERR_clear_error();
1624             ENGINE_load_builtin_engines();
1625             eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1626         }
1627         if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
1628             ERR_clear_error();
1629     }
1630 # endif
1631 #endif
1632     /*
1633      * Default is to connect to non-RI servers. When RI is more widely
1634      * deployed might change this.
1635      */
1636     ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
1637
1638     return (ret);
1639  err:
1640     SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
1641  err2:
1642     if (ret != NULL)
1643         SSL_CTX_free(ret);
1644     return (NULL);
1645 }
1646
1647 #if 0
1648 static void SSL_COMP_free(SSL_COMP *comp)
1649 {
1650     OPENSSL_free(comp);
1651 }
1652 #endif
1653
1654 void SSL_CTX_free(SSL_CTX *a)
1655 {
1656     int i;
1657
1658     if (a == NULL)
1659         return;
1660
1661     i = CRYPTO_add(&a->references, -1, CRYPTO_LOCK_SSL_CTX);
1662 #ifdef REF_PRINT
1663     REF_PRINT("SSL_CTX", a);
1664 #endif
1665     if (i > 0)
1666         return;
1667 #ifdef REF_CHECK
1668     if (i < 0) {
1669         fprintf(stderr, "SSL_CTX_free, bad reference count\n");
1670         abort();                /* ok */
1671     }
1672 #endif
1673
1674     if (a->param)
1675         X509_VERIFY_PARAM_free(a->param);
1676
1677     /*
1678      * Free internal session cache. However: the remove_cb() may reference
1679      * the ex_data of SSL_CTX, thus the ex_data store can only be removed
1680      * after the sessions were flushed.
1681      * As the ex_data handling routines might also touch the session cache,
1682      * the most secure solution seems to be: empty (flush) the cache, then
1683      * free ex_data, then finally free the cache.
1684      * (See ticket [openssl.org #212].)
1685      */
1686     if (a->sessions != NULL)
1687         SSL_CTX_flush_sessions(a, 0);
1688
1689     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
1690
1691     if (a->sessions != NULL)
1692         lh_free(a->sessions);
1693
1694     if (a->cert_store != NULL)
1695         X509_STORE_free(a->cert_store);
1696     if (a->cipher_list != NULL)
1697         sk_SSL_CIPHER_free(a->cipher_list);
1698     if (a->cipher_list_by_id != NULL)
1699         sk_SSL_CIPHER_free(a->cipher_list_by_id);
1700     if (a->cert != NULL)
1701         ssl_cert_free(a->cert);
1702     if (a->client_CA != NULL)
1703         sk_X509_NAME_pop_free(a->client_CA, X509_NAME_free);
1704     if (a->extra_certs != NULL)
1705         sk_X509_pop_free(a->extra_certs, X509_free);
1706 #if 0                           /* This should never be done, since it
1707                                  * removes a global database */
1708     if (a->comp_methods != NULL)
1709         sk_SSL_COMP_pop_free(a->comp_methods, SSL_COMP_free);
1710 #else
1711     a->comp_methods = NULL;
1712 #endif
1713 #ifndef OPENSSL_NO_ENGINE
1714     if (a->client_cert_engine)
1715         ENGINE_finish(a->client_cert_engine);
1716 #endif
1717     OPENSSL_free(a);
1718 }
1719
1720 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
1721 {
1722     ctx->default_passwd_callback = cb;
1723 }
1724
1725 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
1726 {
1727     ctx->default_passwd_callback_userdata = u;
1728 }
1729
1730 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
1731                                       int (*cb) (X509_STORE_CTX *, void *),
1732                                       void *arg)
1733 {
1734     ctx->app_verify_callback = cb;
1735     ctx->app_verify_arg = arg;
1736 }
1737
1738 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
1739                         int (*cb) (int, X509_STORE_CTX *))
1740 {
1741     ctx->verify_mode = mode;
1742     ctx->default_verify_callback = cb;
1743 }
1744
1745 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
1746 {
1747     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
1748 }
1749
1750 void ssl_set_cert_masks(CERT *c, SSL_CIPHER *cipher)
1751 {
1752     CERT_PKEY *cpk;
1753     int rsa_enc, rsa_tmp, rsa_sign, dh_tmp, dh_rsa, dh_dsa, dsa_sign;
1754     int rsa_enc_export, dh_rsa_export, dh_dsa_export;
1755     int rsa_tmp_export, dh_tmp_export, kl;
1756     unsigned long mask, emask;
1757     int have_ecc_cert, ecdh_ok, ecdsa_ok, ecc_pkey_size;
1758 #ifndef OPENSSL_NO_ECDH
1759     int have_ecdh_tmp;
1760 #endif
1761     X509 *x = NULL;
1762     EVP_PKEY *ecc_pkey = NULL;
1763     int signature_nid = 0;
1764
1765     if (c == NULL)
1766         return;
1767
1768     kl = SSL_C_EXPORT_PKEYLENGTH(cipher);
1769
1770 #ifndef OPENSSL_NO_RSA
1771     rsa_tmp = (c->rsa_tmp != NULL || c->rsa_tmp_cb != NULL);
1772     rsa_tmp_export = (c->rsa_tmp_cb != NULL ||
1773                       (rsa_tmp && RSA_size(c->rsa_tmp) * 8 <= kl));
1774 #else
1775     rsa_tmp = rsa_tmp_export = 0;
1776 #endif
1777 #ifndef OPENSSL_NO_DH
1778     dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL);
1779     dh_tmp_export = (c->dh_tmp_cb != NULL ||
1780                      (dh_tmp && DH_size(c->dh_tmp) * 8 <= kl));
1781 #else
1782     dh_tmp = dh_tmp_export = 0;
1783 #endif
1784
1785 #ifndef OPENSSL_NO_ECDH
1786     have_ecdh_tmp = (c->ecdh_tmp != NULL || c->ecdh_tmp_cb != NULL);
1787 #endif
1788     cpk = &(c->pkeys[SSL_PKEY_RSA_ENC]);
1789     rsa_enc = (cpk->x509 != NULL && cpk->privatekey != NULL);
1790     rsa_enc_export = (rsa_enc && EVP_PKEY_size(cpk->privatekey) * 8 <= kl);
1791     cpk = &(c->pkeys[SSL_PKEY_RSA_SIGN]);
1792     rsa_sign = (cpk->x509 != NULL && cpk->privatekey != NULL);
1793     cpk = &(c->pkeys[SSL_PKEY_DSA_SIGN]);
1794     dsa_sign = (cpk->x509 != NULL && cpk->privatekey != NULL);
1795     cpk = &(c->pkeys[SSL_PKEY_DH_RSA]);
1796     dh_rsa = (cpk->x509 != NULL && cpk->privatekey != NULL);
1797     dh_rsa_export = (dh_rsa && EVP_PKEY_size(cpk->privatekey) * 8 <= kl);
1798     cpk = &(c->pkeys[SSL_PKEY_DH_DSA]);
1799 /* FIX THIS EAY EAY EAY */
1800     dh_dsa = (cpk->x509 != NULL && cpk->privatekey != NULL);
1801     dh_dsa_export = (dh_dsa && EVP_PKEY_size(cpk->privatekey) * 8 <= kl);
1802     cpk = &(c->pkeys[SSL_PKEY_ECC]);
1803     have_ecc_cert = (cpk->x509 != NULL && cpk->privatekey != NULL);
1804     mask = 0;
1805     emask = 0;
1806
1807 #ifdef CIPHER_DEBUG
1808     printf("rt=%d rte=%d dht=%d re=%d ree=%d rs=%d ds=%d dhr=%d dhd=%d\n",
1809            rsa_tmp, rsa_tmp_export, dh_tmp,
1810            rsa_enc, rsa_enc_export, rsa_sign, dsa_sign, dh_rsa, dh_dsa);
1811 #endif
1812
1813     if (rsa_enc || (rsa_tmp && rsa_sign))
1814         mask |= SSL_kRSA;
1815     if (rsa_enc_export || (rsa_tmp_export && (rsa_sign || rsa_enc)))
1816         emask |= SSL_kRSA;
1817
1818 #if 0
1819     /* The match needs to be both kEDH and aRSA or aDSA, so don't worry */
1820     if ((dh_tmp || dh_rsa || dh_dsa) && (rsa_enc || rsa_sign || dsa_sign))
1821         mask |= SSL_kEDH;
1822     if ((dh_tmp_export || dh_rsa_export || dh_dsa_export) &&
1823         (rsa_enc || rsa_sign || dsa_sign))
1824         emask |= SSL_kEDH;
1825 #endif
1826
1827     if (dh_tmp_export)
1828         emask |= SSL_kEDH;
1829
1830     if (dh_tmp)
1831         mask |= SSL_kEDH;
1832
1833     if (dh_rsa)
1834         mask |= SSL_kDHr;
1835     if (dh_rsa_export)
1836         emask |= SSL_kDHr;
1837
1838     if (dh_dsa)
1839         mask |= SSL_kDHd;
1840     if (dh_dsa_export)
1841         emask |= SSL_kDHd;
1842
1843     if (rsa_enc || rsa_sign) {
1844         mask |= SSL_aRSA;
1845         emask |= SSL_aRSA;
1846     }
1847
1848     if (dsa_sign) {
1849         mask |= SSL_aDSS;
1850         emask |= SSL_aDSS;
1851     }
1852
1853     mask |= SSL_aNULL;
1854     emask |= SSL_aNULL;
1855
1856 #ifndef OPENSSL_NO_KRB5
1857     mask |= SSL_kKRB5 | SSL_aKRB5;
1858     emask |= SSL_kKRB5 | SSL_aKRB5;
1859 #endif
1860
1861     /*
1862      * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
1863      * depending on the key usage extension.
1864      */
1865     if (have_ecc_cert) {
1866         /* This call populates extension flags (ex_flags) */
1867         x = (c->pkeys[SSL_PKEY_ECC]).x509;
1868         X509_check_purpose(x, -1, 0);
1869         ecdh_ok = (x->ex_flags & EXFLAG_KUSAGE) ?
1870             (x->ex_kusage & X509v3_KU_KEY_AGREEMENT) : 1;
1871         ecdsa_ok = (x->ex_flags & EXFLAG_KUSAGE) ?
1872             (x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE) : 1;
1873         ecc_pkey = X509_get_pubkey(x);
1874         ecc_pkey_size = (ecc_pkey != NULL) ? EVP_PKEY_bits(ecc_pkey) : 0;
1875         EVP_PKEY_free(ecc_pkey);
1876         if ((x->sig_alg) && (x->sig_alg->algorithm))
1877             signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
1878 #ifndef OPENSSL_NO_ECDH
1879         if (ecdh_ok) {
1880             if ((signature_nid == NID_md5WithRSAEncryption) ||
1881                 (signature_nid == NID_md4WithRSAEncryption) ||
1882                 (signature_nid == NID_md2WithRSAEncryption)) {
1883                 mask |= SSL_kECDH | SSL_aRSA;
1884                 if (ecc_pkey_size <= 163)
1885                     emask |= SSL_kECDH | SSL_aRSA;
1886             }
1887             if (signature_nid == NID_ecdsa_with_SHA1) {
1888                 mask |= SSL_kECDH | SSL_aECDSA;
1889                 if (ecc_pkey_size <= 163)
1890                     emask |= SSL_kECDH | SSL_aECDSA;
1891             }
1892         }
1893 #endif
1894 #ifndef OPENSSL_NO_ECDSA
1895         if (ecdsa_ok) {
1896             mask |= SSL_aECDSA;
1897             emask |= SSL_aECDSA;
1898         }
1899 #endif
1900     }
1901 #ifndef OPENSSL_NO_ECDH
1902     if (have_ecdh_tmp) {
1903         mask |= SSL_kECDHE;
1904         emask |= SSL_kECDHE;
1905     }
1906 #endif
1907     c->mask = mask;
1908     c->export_mask = emask;
1909     c->valid = 1;
1910 }
1911
1912 /* This handy macro borrowed from crypto/x509v3/v3_purp.c */
1913 #define ku_reject(x, usage) \
1914         (((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
1915
1916 int check_srvr_ecc_cert_and_alg(X509 *x, SSL_CIPHER *cs)
1917 {
1918     unsigned long alg = cs->algorithms;
1919     EVP_PKEY *pkey = NULL;
1920     int keysize = 0;
1921     int signature_nid = 0;
1922
1923     if (SSL_C_IS_EXPORT(cs)) {
1924         /* ECDH key length in export ciphers must be <= 163 bits */
1925         pkey = X509_get_pubkey(x);
1926         if (pkey == NULL)
1927             return 0;
1928         keysize = EVP_PKEY_bits(pkey);
1929         EVP_PKEY_free(pkey);
1930         if (keysize > 163)
1931             return 0;
1932     }
1933
1934     /* This call populates the ex_flags field correctly */
1935     X509_check_purpose(x, -1, 0);
1936     if ((x->sig_alg) && (x->sig_alg->algorithm))
1937         signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
1938     if (alg & SSL_kECDH) {
1939         /* key usage, if present, must allow key agreement */
1940         if (ku_reject(x, X509v3_KU_KEY_AGREEMENT)) {
1941             return 0;
1942         }
1943         if (alg & SSL_aECDSA) {
1944             /* signature alg must be ECDSA */
1945             if (signature_nid != NID_ecdsa_with_SHA1) {
1946                 return 0;
1947             }
1948         }
1949         if (alg & SSL_aRSA) {
1950             /* signature alg must be RSA */
1951             if ((signature_nid != NID_md5WithRSAEncryption) &&
1952                 (signature_nid != NID_md4WithRSAEncryption) &&
1953                 (signature_nid != NID_md2WithRSAEncryption)) {
1954                 return 0;
1955             }
1956         }
1957     } else if (alg & SSL_aECDSA) {
1958         /* key usage, if present, must allow signing */
1959         if (ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE)) {
1960             return 0;
1961         }
1962     }
1963
1964     return 1;                   /* all checks are ok */
1965 }
1966
1967 /* THIS NEEDS CLEANING UP */
1968 CERT_PKEY *ssl_get_server_send_pkey(const SSL *s)
1969 {
1970     unsigned long alg, kalg;
1971     CERT *c;
1972     int i;
1973
1974     c = s->cert;
1975     ssl_set_cert_masks(c, s->s3->tmp.new_cipher);
1976     alg = s->s3->tmp.new_cipher->algorithms;
1977     kalg = alg & (SSL_MKEY_MASK | SSL_AUTH_MASK);
1978
1979     if (kalg & SSL_kECDH) {
1980         /*
1981          * we don't need to look at SSL_kECDHE since no certificate is
1982          * needed for anon ECDH and for authenticated ECDHE, the check for
1983          * the auth algorithm will set i correctly NOTE: For ECDH-RSA, we
1984          * need an ECC not an RSA cert but for ECDHE-RSA we need an RSA cert.
1985          * Placing the checks for SSL_kECDH before RSA checks ensures the
1986          * correct cert is chosen.
1987          */
1988         i = SSL_PKEY_ECC;
1989     } else if (kalg & SSL_aECDSA) {
1990         i = SSL_PKEY_ECC;
1991     } else if (kalg & SSL_kDHr)
1992         i = SSL_PKEY_DH_RSA;
1993     else if (kalg & SSL_kDHd)
1994         i = SSL_PKEY_DH_DSA;
1995     else if (kalg & SSL_aDSS)
1996         i = SSL_PKEY_DSA_SIGN;
1997     else if (kalg & SSL_aRSA) {
1998         if (c->pkeys[SSL_PKEY_RSA_ENC].x509 == NULL)
1999             i = SSL_PKEY_RSA_SIGN;
2000         else
2001             i = SSL_PKEY_RSA_ENC;
2002     } else if (kalg & SSL_aKRB5) {
2003         /* VRS something else here? */
2004         return (NULL);
2005     } else {                    /* if (kalg & SSL_aNULL) */
2006
2007         SSLerr(SSL_F_SSL_GET_SERVER_SEND_PKEY, ERR_R_INTERNAL_ERROR);
2008         return (NULL);
2009     }
2010
2011     return c->pkeys + i;
2012 }
2013
2014 X509 *ssl_get_server_send_cert(const SSL *s)
2015 {
2016     CERT_PKEY *cpk;
2017     cpk = ssl_get_server_send_pkey(s);
2018     if (!cpk)
2019         return NULL;
2020     return cpk->x509;
2021 }
2022
2023 EVP_PKEY *ssl_get_sign_pkey(SSL *s, SSL_CIPHER *cipher)
2024 {
2025     unsigned long alg;
2026     CERT *c;
2027
2028     alg = cipher->algorithms;
2029     c = s->cert;
2030
2031     if ((alg & SSL_aDSS) && (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
2032         return (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey);
2033     else if (alg & SSL_aRSA) {
2034         if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
2035             return (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey);
2036         else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
2037             return (c->pkeys[SSL_PKEY_RSA_ENC].privatekey);
2038         else
2039             return (NULL);
2040     } else if ((alg & SSL_aECDSA) &&
2041                (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2042         return (c->pkeys[SSL_PKEY_ECC].privatekey);
2043     else {                      /* if (alg & SSL_aNULL) */
2044
2045         SSLerr(SSL_F_SSL_GET_SIGN_PKEY, ERR_R_INTERNAL_ERROR);
2046         return (NULL);
2047     }
2048 }
2049
2050 void ssl_update_cache(SSL *s, int mode)
2051 {
2052     int i;
2053
2054     /*
2055      * If the session_id_length is 0, we are not supposed to cache it, and it
2056      * would be rather hard to do anyway :-)
2057      */
2058     if (s->session->session_id_length == 0)
2059         return;
2060
2061     i = s->ctx->session_cache_mode;
2062     if ((i & mode) && (!s->hit)
2063         && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
2064             || SSL_CTX_add_session(s->ctx, s->session))
2065         && (s->ctx->new_session_cb != NULL)) {
2066         CRYPTO_add(&s->session->references, 1, CRYPTO_LOCK_SSL_SESSION);
2067         if (!s->ctx->new_session_cb(s, s->session))
2068             SSL_SESSION_free(s->session);
2069     }
2070
2071     /* auto flush every 255 connections */
2072     if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
2073         if ((((mode & SSL_SESS_CACHE_CLIENT)
2074               ? s->ctx->stats.sess_connect_good
2075               : s->ctx->stats.sess_accept_good) & 0xff) == 0xff) {
2076             SSL_CTX_flush_sessions(s->ctx, (unsigned long)time(NULL));
2077         }
2078     }
2079 }
2080
2081 SSL_METHOD *SSL_get_ssl_method(SSL *s)
2082 {
2083     return (s->method);
2084 }
2085
2086 int SSL_set_ssl_method(SSL *s, SSL_METHOD *meth)
2087 {
2088     int conn = -1;
2089     int ret = 1;
2090
2091     if (s->method != meth) {
2092         if (s->handshake_func != NULL)
2093             conn = (s->handshake_func == s->method->ssl_connect);
2094
2095         if (s->method->version == meth->version)
2096             s->method = meth;
2097         else {
2098             s->method->ssl_free(s);
2099             s->method = meth;
2100             ret = s->method->ssl_new(s);
2101         }
2102
2103         if (conn == 1)
2104             s->handshake_func = meth->ssl_connect;
2105         else if (conn == 0)
2106             s->handshake_func = meth->ssl_accept;
2107     }
2108     return (ret);
2109 }
2110
2111 int SSL_get_error(const SSL *s, int i)
2112 {
2113     int reason;
2114     unsigned long l;
2115     BIO *bio;
2116
2117     if (i > 0)
2118         return (SSL_ERROR_NONE);
2119
2120     /*
2121      * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
2122      * where we do encode the error
2123      */
2124     if ((l = ERR_peek_error()) != 0) {
2125         if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2126             return (SSL_ERROR_SYSCALL);
2127         else
2128             return (SSL_ERROR_SSL);
2129     }
2130
2131     if ((i < 0) && SSL_want_read(s)) {
2132         bio = SSL_get_rbio(s);
2133         if (BIO_should_read(bio))
2134             return (SSL_ERROR_WANT_READ);
2135         else if (BIO_should_write(bio))
2136             /*
2137              * This one doesn't make too much sense ... We never try to write
2138              * to the rbio, and an application program where rbio and wbio
2139              * are separate couldn't even know what it should wait for.
2140              * However if we ever set s->rwstate incorrectly (so that we have
2141              * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
2142              * wbio *are* the same, this test works around that bug; so it
2143              * might be safer to keep it.
2144              */
2145             return (SSL_ERROR_WANT_WRITE);
2146         else if (BIO_should_io_special(bio)) {
2147             reason = BIO_get_retry_reason(bio);
2148             if (reason == BIO_RR_CONNECT)
2149                 return (SSL_ERROR_WANT_CONNECT);
2150             else if (reason == BIO_RR_ACCEPT)
2151                 return (SSL_ERROR_WANT_ACCEPT);
2152             else
2153                 return (SSL_ERROR_SYSCALL); /* unknown */
2154         }
2155     }
2156
2157     if ((i < 0) && SSL_want_write(s)) {
2158         bio = SSL_get_wbio(s);
2159         if (BIO_should_write(bio))
2160             return (SSL_ERROR_WANT_WRITE);
2161         else if (BIO_should_read(bio))
2162             /*
2163              * See above (SSL_want_read(s) with BIO_should_write(bio))
2164              */
2165             return (SSL_ERROR_WANT_READ);
2166         else if (BIO_should_io_special(bio)) {
2167             reason = BIO_get_retry_reason(bio);
2168             if (reason == BIO_RR_CONNECT)
2169                 return (SSL_ERROR_WANT_CONNECT);
2170             else if (reason == BIO_RR_ACCEPT)
2171                 return (SSL_ERROR_WANT_ACCEPT);
2172             else
2173                 return (SSL_ERROR_SYSCALL);
2174         }
2175     }
2176     if ((i < 0) && SSL_want_x509_lookup(s)) {
2177         return (SSL_ERROR_WANT_X509_LOOKUP);
2178     }
2179
2180     if (i == 0) {
2181         if (s->version == SSL2_VERSION) {
2182             /* assume it is the socket being closed */
2183             return (SSL_ERROR_ZERO_RETURN);
2184         } else {
2185             if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2186                 (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
2187                 return (SSL_ERROR_ZERO_RETURN);
2188         }
2189     }
2190     return (SSL_ERROR_SYSCALL);
2191 }
2192
2193 int SSL_do_handshake(SSL *s)
2194 {
2195     int ret = 1;
2196
2197     if (s->handshake_func == NULL) {
2198         SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
2199         return (-1);
2200     }
2201
2202     s->method->ssl_renegotiate_check(s);
2203
2204     if (SSL_in_init(s) || SSL_in_before(s)) {
2205         ret = s->handshake_func(s);
2206     }
2207     return (ret);
2208 }
2209
2210 /*
2211  * For the next 2 functions, SSL_clear() sets shutdown and so one of these
2212  * calls will reset it
2213  */
2214 void SSL_set_accept_state(SSL *s)
2215 {
2216     s->server = 1;
2217     s->shutdown = 0;
2218     s->state = SSL_ST_ACCEPT | SSL_ST_BEFORE;
2219     s->handshake_func = s->method->ssl_accept;
2220     /* clear the current cipher */
2221     ssl_clear_cipher_ctx(s);
2222 }
2223
2224 void SSL_set_connect_state(SSL *s)
2225 {
2226     s->server = 0;
2227     s->shutdown = 0;
2228     s->state = SSL_ST_CONNECT | SSL_ST_BEFORE;
2229     s->handshake_func = s->method->ssl_connect;
2230     /* clear the current cipher */
2231     ssl_clear_cipher_ctx(s);
2232 }
2233
2234 int ssl_undefined_function(SSL *s)
2235 {
2236     SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2237     return (0);
2238 }
2239
2240 int ssl_undefined_void_function(void)
2241 {
2242     SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
2243            ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2244     return (0);
2245 }
2246
2247 int ssl_undefined_const_function(const SSL *s)
2248 {
2249     SSLerr(SSL_F_SSL_UNDEFINED_CONST_FUNCTION,
2250            ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2251     return (0);
2252 }
2253
2254 SSL_METHOD *ssl_bad_method(int ver)
2255 {
2256     SSLerr(SSL_F_SSL_BAD_METHOD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2257     return (NULL);
2258 }
2259
2260 const char *SSL_get_version(const SSL *s)
2261 {
2262     if (s->version == TLS1_VERSION)
2263         return ("TLSv1");
2264     else if (s->version == SSL3_VERSION)
2265         return ("SSLv3");
2266     else if (s->version == SSL2_VERSION)
2267         return ("SSLv2");
2268     else
2269         return ("unknown");
2270 }
2271
2272 SSL *SSL_dup(SSL *s)
2273 {
2274     STACK_OF(X509_NAME) *sk;
2275     X509_NAME *xn;
2276     SSL *ret;
2277     int i;
2278
2279     if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
2280         return (NULL);
2281
2282     ret->version = s->version;
2283     ret->type = s->type;
2284     ret->method = s->method;
2285
2286     if (s->session != NULL) {
2287         /* This copies session-id, SSL_METHOD, sid_ctx, and 'cert' */
2288         SSL_copy_session_id(ret, s);
2289     } else {
2290         /*
2291          * No session has been established yet, so we have to expect that
2292          * s->cert or ret->cert will be changed later -- they should not both
2293          * point to the same object, and thus we can't use
2294          * SSL_copy_session_id.
2295          */
2296
2297         ret->method->ssl_free(ret);
2298         ret->method = s->method;
2299         ret->method->ssl_new(ret);
2300
2301         if (s->cert != NULL) {
2302             if (ret->cert != NULL) {
2303                 ssl_cert_free(ret->cert);
2304             }
2305             ret->cert = ssl_cert_dup(s->cert);
2306             if (ret->cert == NULL)
2307                 goto err;
2308         }
2309
2310         SSL_set_session_id_context(ret, s->sid_ctx, s->sid_ctx_length);
2311     }
2312
2313     ret->options = s->options;
2314     ret->mode = s->mode;
2315     SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
2316     SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
2317     ret->msg_callback = s->msg_callback;
2318     ret->msg_callback_arg = s->msg_callback_arg;
2319     SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
2320     SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
2321     ret->generate_session_id = s->generate_session_id;
2322
2323     SSL_set_info_callback(ret, SSL_get_info_callback(s));
2324
2325     ret->debug = s->debug;
2326
2327     /* copy app data, a little dangerous perhaps */
2328     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
2329         goto err;
2330
2331     /* setup rbio, and wbio */
2332     if (s->rbio != NULL) {
2333         if (!BIO_dup_state(s->rbio, (char *)&ret->rbio))
2334             goto err;
2335     }
2336     if (s->wbio != NULL) {
2337         if (s->wbio != s->rbio) {
2338             if (!BIO_dup_state(s->wbio, (char *)&ret->wbio))
2339                 goto err;
2340         } else
2341             ret->wbio = ret->rbio;
2342     }
2343     ret->rwstate = s->rwstate;
2344     ret->in_handshake = s->in_handshake;
2345     ret->handshake_func = s->handshake_func;
2346     ret->server = s->server;
2347     ret->new_session = s->new_session;
2348     ret->quiet_shutdown = s->quiet_shutdown;
2349     ret->shutdown = s->shutdown;
2350     ret->state = s->state;      /* SSL_dup does not really work at any state,
2351                                  * though */
2352     ret->rstate = s->rstate;
2353     ret->init_num = 0;          /* would have to copy ret->init_buf,
2354                                  * ret->init_msg, ret->init_num,
2355                                  * ret->init_off */
2356     ret->hit = s->hit;
2357
2358     X509_VERIFY_PARAM_inherit(ret->param, s->param);
2359
2360     /* dup the cipher_list and cipher_list_by_id stacks */
2361     if (s->cipher_list != NULL) {
2362         if ((ret->cipher_list = sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
2363             goto err;
2364     }
2365     if (s->cipher_list_by_id != NULL)
2366         if ((ret->cipher_list_by_id = sk_SSL_CIPHER_dup(s->cipher_list_by_id))
2367             == NULL)
2368             goto err;
2369
2370     /* Dup the client_CA list */
2371     if (s->client_CA != NULL) {
2372         if ((sk = sk_X509_NAME_dup(s->client_CA)) == NULL)
2373             goto err;
2374         ret->client_CA = sk;
2375         for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2376             xn = sk_X509_NAME_value(sk, i);
2377             if (sk_X509_NAME_set(sk, i, X509_NAME_dup(xn)) == NULL) {
2378                 X509_NAME_free(xn);
2379                 goto err;
2380             }
2381         }
2382     }
2383
2384     if (0) {
2385  err:
2386         if (ret != NULL)
2387             SSL_free(ret);
2388         ret = NULL;
2389     }
2390     return (ret);
2391 }
2392
2393 void ssl_clear_cipher_ctx(SSL *s)
2394 {
2395     if (s->enc_read_ctx != NULL) {
2396         EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
2397         OPENSSL_free(s->enc_read_ctx);
2398         s->enc_read_ctx = NULL;
2399     }
2400     if (s->enc_write_ctx != NULL) {
2401         EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
2402         OPENSSL_free(s->enc_write_ctx);
2403         s->enc_write_ctx = NULL;
2404     }
2405 #ifndef OPENSSL_NO_COMP
2406     if (s->expand != NULL) {
2407         COMP_CTX_free(s->expand);
2408         s->expand = NULL;
2409     }
2410     if (s->compress != NULL) {
2411         COMP_CTX_free(s->compress);
2412         s->compress = NULL;
2413     }
2414 #endif
2415 }
2416
2417 /* Fix this function so that it takes an optional type parameter */
2418 X509 *SSL_get_certificate(const SSL *s)
2419 {
2420     if (s->cert != NULL)
2421         return (s->cert->key->x509);
2422     else
2423         return (NULL);
2424 }
2425
2426 /* Fix this function so that it takes an optional type parameter */
2427 EVP_PKEY *SSL_get_privatekey(SSL *s)
2428 {
2429     if (s->cert != NULL)
2430         return (s->cert->key->privatekey);
2431     else
2432         return (NULL);
2433 }
2434
2435 SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
2436 {
2437     if ((s->session != NULL) && (s->session->cipher != NULL))
2438         return (s->session->cipher);
2439     return (NULL);
2440 }
2441
2442 #ifdef OPENSSL_NO_COMP
2443 const void *SSL_get_current_compression(SSL *s)
2444 {
2445     return NULL;
2446 }
2447
2448 const void *SSL_get_current_expansion(SSL *s)
2449 {
2450     return NULL;
2451 }
2452 #else
2453
2454 const COMP_METHOD *SSL_get_current_compression(SSL *s)
2455 {
2456     if (s->compress != NULL)
2457         return (s->compress->meth);
2458     return (NULL);
2459 }
2460
2461 const COMP_METHOD *SSL_get_current_expansion(SSL *s)
2462 {
2463     if (s->expand != NULL)
2464         return (s->expand->meth);
2465     return (NULL);
2466 }
2467 #endif
2468
2469 int ssl_init_wbio_buffer(SSL *s, int push)
2470 {
2471     BIO *bbio;
2472
2473     if (s->bbio == NULL) {
2474         bbio = BIO_new(BIO_f_buffer());
2475         if (bbio == NULL)
2476             return (0);
2477         s->bbio = bbio;
2478     } else {
2479         bbio = s->bbio;
2480         if (s->bbio == s->wbio)
2481             s->wbio = BIO_pop(s->wbio);
2482     }
2483     (void)BIO_reset(bbio);
2484 /*      if (!BIO_set_write_buffer_size(bbio,16*1024)) */
2485     if (!BIO_set_read_buffer_size(bbio, 1)) {
2486         SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
2487         return (0);
2488     }
2489     if (push) {
2490         if (s->wbio != bbio)
2491             s->wbio = BIO_push(bbio, s->wbio);
2492     } else {
2493         if (s->wbio == bbio)
2494             s->wbio = BIO_pop(bbio);
2495     }
2496     return (1);
2497 }
2498
2499 void ssl_free_wbio_buffer(SSL *s)
2500 {
2501     if (s->bbio == NULL)
2502         return;
2503
2504     if (s->bbio == s->wbio) {
2505         /* remove buffering */
2506         s->wbio = BIO_pop(s->wbio);
2507 #ifdef REF_CHECK                /* not the usual REF_CHECK, but this avoids
2508                                  * adding one more preprocessor symbol */
2509         assert(s->wbio != NULL);
2510 #endif
2511     }
2512     BIO_free(s->bbio);
2513     s->bbio = NULL;
2514 }
2515
2516 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
2517 {
2518     ctx->quiet_shutdown = mode;
2519 }
2520
2521 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
2522 {
2523     return (ctx->quiet_shutdown);
2524 }
2525
2526 void SSL_set_quiet_shutdown(SSL *s, int mode)
2527 {
2528     s->quiet_shutdown = mode;
2529 }
2530
2531 int SSL_get_quiet_shutdown(const SSL *s)
2532 {
2533     return (s->quiet_shutdown);
2534 }
2535
2536 void SSL_set_shutdown(SSL *s, int mode)
2537 {
2538     s->shutdown = mode;
2539 }
2540
2541 int SSL_get_shutdown(const SSL *s)
2542 {
2543     return (s->shutdown);
2544 }
2545
2546 int SSL_version(const SSL *s)
2547 {
2548     return (s->version);
2549 }
2550
2551 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
2552 {
2553     return (ssl->ctx);
2554 }
2555
2556 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
2557 {
2558     if (ssl->ctx == ctx)
2559         return ssl->ctx;
2560 #ifndef OPENSSL_NO_TLSEXT
2561     if (ctx == NULL)
2562         ctx = ssl->initial_ctx;
2563 #endif
2564     if (ssl->cert != NULL)
2565         ssl_cert_free(ssl->cert);
2566     ssl->cert = ssl_cert_dup(ctx->cert);
2567     CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
2568     if (ssl->ctx != NULL)
2569         SSL_CTX_free(ssl->ctx); /* decrement reference count */
2570     ssl->ctx = ctx;
2571     return (ssl->ctx);
2572 }
2573
2574 #ifndef OPENSSL_NO_STDIO
2575 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
2576 {
2577     return (X509_STORE_set_default_paths(ctx->cert_store));
2578 }
2579
2580 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
2581                                   const char *CApath)
2582 {
2583     return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
2584 }
2585 #endif
2586
2587 void SSL_set_info_callback(SSL *ssl,
2588                            void (*cb) (const SSL *ssl, int type, int val))
2589 {
2590     ssl->info_callback = cb;
2591 }
2592
2593 /*
2594  * One compiler (Diab DCC) doesn't like argument names in returned function
2595  * pointer.
2596  */
2597 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
2598                                                int /* type */ ,
2599                                                int /* val */ ) {
2600     return ssl->info_callback;
2601 }
2602
2603 int SSL_state(const SSL *ssl)
2604 {
2605     return (ssl->state);
2606 }
2607
2608 void SSL_set_verify_result(SSL *ssl, long arg)
2609 {
2610     ssl->verify_result = arg;
2611 }
2612
2613 long SSL_get_verify_result(const SSL *ssl)
2614 {
2615     return (ssl->verify_result);
2616 }
2617
2618 int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2619                          CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
2620 {
2621     return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp,
2622                                    new_func, dup_func, free_func);
2623 }
2624
2625 int SSL_set_ex_data(SSL *s, int idx, void *arg)
2626 {
2627     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
2628 }
2629
2630 void *SSL_get_ex_data(const SSL *s, int idx)
2631 {
2632     return (CRYPTO_get_ex_data(&s->ex_data, idx));
2633 }
2634
2635 int SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2636                              CRYPTO_EX_dup *dup_func,
2637                              CRYPTO_EX_free *free_func)
2638 {
2639     return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp,
2640                                    new_func, dup_func, free_func);
2641 }
2642
2643 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
2644 {
2645     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
2646 }
2647
2648 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
2649 {
2650     return (CRYPTO_get_ex_data(&s->ex_data, idx));
2651 }
2652
2653 int ssl_ok(SSL *s)
2654 {
2655     return (1);
2656 }
2657
2658 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
2659 {
2660     return (ctx->cert_store);
2661 }
2662
2663 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
2664 {
2665     if (ctx->cert_store != NULL)
2666         X509_STORE_free(ctx->cert_store);
2667     ctx->cert_store = store;
2668 }
2669
2670 int SSL_want(const SSL *s)
2671 {
2672     return (s->rwstate);
2673 }
2674
2675 /**
2676  * \brief Set the callback for generating temporary RSA keys.
2677  * \param ctx the SSL context.
2678  * \param cb the callback
2679  */
2680
2681 #ifndef OPENSSL_NO_RSA
2682 void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*cb) (SSL *ssl,
2683                                                             int is_export,
2684                                                             int keylength))
2685 {
2686     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_RSA_CB, (void (*)(void))cb);
2687 }
2688
2689 void SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb) (SSL *ssl,
2690                                                     int is_export,
2691                                                     int keylength))
2692 {
2693     SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_RSA_CB, (void (*)(void))cb);
2694 }
2695 #endif
2696
2697 #ifdef DOXYGEN
2698 /**
2699  * \brief The RSA temporary key callback function.
2700  * \param ssl the SSL session.
2701  * \param is_export \c TRUE if the temp RSA key is for an export ciphersuite.
2702  * \param keylength if \c is_export is \c TRUE, then \c keylength is the size
2703  * of the required key in bits.
2704  * \return the temporary RSA key.
2705  * \sa SSL_CTX_set_tmp_rsa_callback, SSL_set_tmp_rsa_callback
2706  */
2707
2708 RSA *cb(SSL *ssl, int is_export, int keylength)
2709 {
2710 }
2711 #endif
2712
2713 /**
2714  * \brief Set the callback for generating temporary DH keys.
2715  * \param ctx the SSL context.
2716  * \param dh the callback
2717  */
2718
2719 #ifndef OPENSSL_NO_DH
2720 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
2721                                  DH *(*dh) (SSL *ssl, int is_export,
2722                                             int keylength))
2723 {
2724     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
2725 }
2726
2727 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
2728                                                   int keylength))
2729 {
2730     SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
2731 }
2732 #endif
2733
2734 #ifndef OPENSSL_NO_ECDH
2735 void SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx,
2736                                    EC_KEY *(*ecdh) (SSL *ssl, int is_export,
2737                                                     int keylength))
2738 {
2739     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH_CB,
2740                           (void (*)(void))ecdh);
2741 }
2742
2743 void SSL_set_tmp_ecdh_callback(SSL *ssl,
2744                                EC_KEY *(*ecdh) (SSL *ssl, int is_export,
2745                                                 int keylength))
2746 {
2747     SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH_CB, (void (*)(void))ecdh);
2748 }
2749 #endif
2750
2751 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
2752                               void (*cb) (int write_p, int version,
2753                                           int content_type, const void *buf,
2754                                           size_t len, SSL *ssl, void *arg))
2755 {
2756     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
2757 }
2758
2759 void SSL_set_msg_callback(SSL *ssl,
2760                           void (*cb) (int write_p, int version,
2761                                       int content_type, const void *buf,
2762                                       size_t len, SSL *ssl, void *arg))
2763 {
2764     SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
2765 }
2766
2767 #if defined(_WINDLL) && defined(OPENSSL_SYS_WIN16)
2768 # include "../crypto/bio/bss_file.c"
2769 #endif
2770
2771 IMPLEMENT_STACK_OF(SSL_CIPHER)
2772 IMPLEMENT_STACK_OF(SSL_COMP)