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