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