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