The wrong ifdef is used to guard usage of PSK code
[openssl.git] / ssl / ssl_lib.c
1 /*
2  * ! \file ssl/ssl_lib.c \brief Version independent SSL functions.
3  */
4 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5  * All rights reserved.
6  *
7  * This package is an SSL implementation written
8  * by Eric Young (eay@cryptsoft.com).
9  * The implementation was written so as to conform with Netscapes SSL.
10  *
11  * This library is free for commercial and non-commercial use as long as
12  * the following conditions are aheared to.  The following conditions
13  * apply to all code found in this distribution, be it the RC4, RSA,
14  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
15  * included with this distribution is covered by the same copyright terms
16  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
17  *
18  * Copyright remains Eric Young's, and as such any Copyright notices in
19  * the code are not to be removed.
20  * If this package is used in a product, Eric Young should be given attribution
21  * as the author of the parts of the library used.
22  * This can be in the form of a textual message at program startup or
23  * in documentation (online or textual) provided with the package.
24  *
25  * Redistribution and use in source and binary forms, with or without
26  * modification, are permitted provided that the following conditions
27  * are met:
28  * 1. Redistributions of source code must retain the copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. Redistributions in binary form must reproduce the above copyright
31  *    notice, this list of conditions and the following disclaimer in the
32  *    documentation and/or other materials provided with the distribution.
33  * 3. All advertising materials mentioning features or use of this software
34  *    must display the following acknowledgement:
35  *    "This product includes cryptographic software written by
36  *     Eric Young (eay@cryptsoft.com)"
37  *    The word 'cryptographic' can be left out if the rouines from the library
38  *    being used are not cryptographic related :-).
39  * 4. If you include any Windows specific code (or a derivative thereof) from
40  *    the apps directory (application code) you must include an acknowledgement:
41  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
42  *
43  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
44  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
47  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  *
55  * The licence and distribution terms for any publically available version or
56  * derivative of this code cannot be changed.  i.e. this code cannot simply be
57  * copied and put under another distribution licence
58  * [including the GNU Public Licence.]
59  */
60 /* ====================================================================
61  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
62  *
63  * Redistribution and use in source and binary forms, with or without
64  * modification, are permitted provided that the following conditions
65  * are met:
66  *
67  * 1. Redistributions of source code must retain the above copyright
68  *    notice, this list of conditions and the following disclaimer.
69  *
70  * 2. Redistributions in binary form must reproduce the above copyright
71  *    notice, this list of conditions and the following disclaimer in
72  *    the documentation and/or other materials provided with the
73  *    distribution.
74  *
75  * 3. All advertising materials mentioning features or use of this
76  *    software must display the following acknowledgment:
77  *    "This product includes software developed by the OpenSSL Project
78  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
79  *
80  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
81  *    endorse or promote products derived from this software without
82  *    prior written permission. For written permission, please contact
83  *    openssl-core@openssl.org.
84  *
85  * 5. Products derived from this software may not be called "OpenSSL"
86  *    nor may "OpenSSL" appear in their names without prior written
87  *    permission of the OpenSSL Project.
88  *
89  * 6. Redistributions of any form whatsoever must retain the following
90  *    acknowledgment:
91  *    "This product includes software developed by the OpenSSL Project
92  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
93  *
94  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
95  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
96  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
97  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
98  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
99  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
100  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
101  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
102  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
103  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
104  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
105  * OF THE POSSIBILITY OF SUCH DAMAGE.
106  * ====================================================================
107  *
108  * This product includes cryptographic software written by Eric Young
109  * (eay@cryptsoft.com).  This product includes software written by Tim
110  * Hudson (tjh@cryptsoft.com).
111  *
112  */
113 /* ====================================================================
114  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
115  * ECC cipher suite support in OpenSSL originally developed by
116  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
117  */
118 /* ====================================================================
119  * Copyright 2005 Nokia. All rights reserved.
120  *
121  * The portions of the attached software ("Contribution") is developed by
122  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
123  * license.
124  *
125  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
126  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
127  * support (see RFC 4279) to OpenSSL.
128  *
129  * No patent licenses or other rights except those expressly stated in
130  * the OpenSSL open source license shall be deemed granted or received
131  * expressly, by implication, estoppel, or otherwise.
132  *
133  * No assurances are provided by Nokia that the Contribution does not
134  * infringe the patent or other intellectual property rights of any third
135  * party or that the license provides you with all the necessary rights
136  * to make use of the Contribution.
137  *
138  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
139  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
140  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
141  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
142  * OTHERWISE.
143  */
144
145 #ifdef REF_CHECK
146 # include <assert.h>
147 #endif
148 #include <stdio.h>
149 #include "ssl_locl.h"
150 #include "kssl_lcl.h"
151 #include <openssl/objects.h>
152 #include <openssl/lhash.h>
153 #include <openssl/x509v3.h>
154 #include <openssl/rand.h>
155 #include <openssl/ocsp.h>
156 #ifndef OPENSSL_NO_DH
157 # include <openssl/dh.h>
158 #endif
159 #ifndef OPENSSL_NO_ENGINE
160 # include <openssl/engine.h>
161 #endif
162
163 const char *SSL_version_str = OPENSSL_VERSION_TEXT;
164
165 SSL3_ENC_METHOD ssl3_undef_enc_method = {
166     /*
167      * evil casts, but these functions are only called if there's a library
168      * bug
169      */
170     (int (*)(SSL *, int))ssl_undefined_function,
171     (int (*)(SSL *, unsigned char *, int))ssl_undefined_function,
172     ssl_undefined_function,
173     (int (*)(SSL *, unsigned char *, unsigned char *, int))
174         ssl_undefined_function,
175     (int (*)(SSL *, int))ssl_undefined_function,
176     (int (*)(SSL *, const char *, int, unsigned char *))
177         ssl_undefined_function,
178     0,                          /* finish_mac_length */
179     (int (*)(SSL *, int, unsigned char *))ssl_undefined_function,
180     NULL,                       /* client_finished_label */
181     0,                          /* client_finished_label_len */
182     NULL,                       /* server_finished_label */
183     0,                          /* server_finished_label_len */
184     (int (*)(int))ssl_undefined_function,
185     (int (*)(SSL *, unsigned char *, size_t, const char *,
186              size_t, const unsigned char *, size_t,
187              int use_context))ssl_undefined_function,
188 };
189
190 int SSL_clear(SSL *s)
191 {
192     if (s->method == NULL) {
193         SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
194         return (0);
195     }
196
197     if (ssl_clear_bad_session(s)) {
198         SSL_SESSION_free(s->session);
199         s->session = NULL;
200     }
201
202     s->error = 0;
203     s->hit = 0;
204     s->shutdown = 0;
205
206     if (s->renegotiate) {
207         SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
208         return 0;
209     }
210
211     s->type = 0;
212
213     s->state = SSL_ST_BEFORE | ((s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT);
214
215     s->version = s->method->version;
216     s->client_version = s->version;
217     s->rwstate = SSL_NOTHING;
218
219     if (s->init_buf != NULL) {
220         BUF_MEM_free(s->init_buf);
221         s->init_buf = NULL;
222     }
223
224     ssl_clear_cipher_ctx(s);
225     ssl_clear_hash_ctx(&s->read_hash);
226     ssl_clear_hash_ctx(&s->write_hash);
227
228     s->first_packet = 0;
229
230     /*
231      * Check to see if we were changed into a different method, if so, revert
232      * back if we are not doing session-id reuse.
233      */
234     if (!s->in_handshake && (s->session == NULL)
235         && (s->method != s->ctx->method)) {
236         s->method->ssl_free(s);
237         s->method = s->ctx->method;
238         if (!s->method->ssl_new(s))
239             return (0);
240     } else
241         s->method->ssl_clear(s);
242
243     RECORD_LAYER_clear(&s->rlayer);
244
245     return (1);
246 }
247
248 /** Used to change an SSL_CTXs default SSL method type */
249 int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
250 {
251     STACK_OF(SSL_CIPHER) *sk;
252
253     ctx->method = meth;
254
255     sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
256                                 &(ctx->cipher_list_by_id),
257                                 SSL_DEFAULT_CIPHER_LIST, ctx->cert);
258     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
259         SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION,
260                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         SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
272         return (NULL);
273     }
274     if (ctx->method == NULL) {
275         SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
276         return (NULL);
277     }
278
279     s = (SSL *)OPENSSL_malloc(sizeof(SSL));
280     if (s == NULL)
281         goto err;
282     memset(s, 0, sizeof(SSL));
283
284     RECORD_LAYER_init(&s->rlayer, s);
285
286 #ifndef OPENSSL_NO_KRB5
287     s->kssl_ctx = kssl_ctx_new();
288 #endif                          /* OPENSSL_NO_KRB5 */
289
290     s->options = ctx->options;
291     s->mode = ctx->mode;
292     s->max_cert_list = ctx->max_cert_list;
293
294     /*
295      * Earlier library versions used to copy the pointer to the CERT, not
296      * its contents; only when setting new parameters for the per-SSL
297      * copy, ssl_cert_new would be called (and the direct reference to
298      * the per-SSL_CTX settings would be lost, but those still were
299      * indirectly accessed for various purposes, and for that reason they
300      * used to be known as s->ctx->default_cert). Now we don't look at the
301      * SSL_CTX's CERT after having duplicated it once.
302      */
303     s->cert = ssl_cert_dup(ctx->cert);
304     if (s->cert == NULL)
305         goto err;
306
307     RECORD_LAYER_set_read_ahead(&s->rlayer, ctx->read_ahead);
308     s->msg_callback = ctx->msg_callback;
309     s->msg_callback_arg = ctx->msg_callback_arg;
310     s->verify_mode = ctx->verify_mode;
311     s->not_resumable_session_cb = ctx->not_resumable_session_cb;
312     s->sid_ctx_length = ctx->sid_ctx_length;
313     OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx);
314     memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
315     s->verify_callback = ctx->default_verify_callback;
316     s->generate_session_id = ctx->generate_session_id;
317
318     s->param = X509_VERIFY_PARAM_new();
319     if (!s->param)
320         goto err;
321     X509_VERIFY_PARAM_inherit(s->param, ctx->param);
322     s->quiet_shutdown = ctx->quiet_shutdown;
323     s->max_send_fragment = ctx->max_send_fragment;
324
325     CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
326     s->ctx = ctx;
327 #ifndef OPENSSL_NO_TLSEXT
328     s->tlsext_debug_cb = 0;
329     s->tlsext_debug_arg = NULL;
330     s->tlsext_ticket_expected = 0;
331     s->tlsext_status_type = -1;
332     s->tlsext_status_expected = 0;
333     s->tlsext_ocsp_ids = NULL;
334     s->tlsext_ocsp_exts = NULL;
335     s->tlsext_ocsp_resp = NULL;
336     s->tlsext_ocsp_resplen = -1;
337     CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
338     s->initial_ctx = ctx;
339 # ifndef OPENSSL_NO_EC
340     if (ctx->tlsext_ecpointformatlist) {
341         s->tlsext_ecpointformatlist =
342             BUF_memdup(ctx->tlsext_ecpointformatlist,
343                        ctx->tlsext_ecpointformatlist_length);
344         if (!s->tlsext_ecpointformatlist)
345             goto err;
346         s->tlsext_ecpointformatlist_length =
347             ctx->tlsext_ecpointformatlist_length;
348     }
349     if (ctx->tlsext_ellipticcurvelist) {
350         s->tlsext_ellipticcurvelist =
351             BUF_memdup(ctx->tlsext_ellipticcurvelist,
352                        ctx->tlsext_ellipticcurvelist_length);
353         if (!s->tlsext_ellipticcurvelist)
354             goto err;
355         s->tlsext_ellipticcurvelist_length =
356             ctx->tlsext_ellipticcurvelist_length;
357     }
358 # endif
359 # ifndef OPENSSL_NO_NEXTPROTONEG
360     s->next_proto_negotiated = NULL;
361 # endif
362
363     if (s->ctx->alpn_client_proto_list) {
364         s->alpn_client_proto_list =
365             OPENSSL_malloc(s->ctx->alpn_client_proto_list_len);
366         if (s->alpn_client_proto_list == NULL)
367             goto err;
368         memcpy(s->alpn_client_proto_list, s->ctx->alpn_client_proto_list,
369                s->ctx->alpn_client_proto_list_len);
370         s->alpn_client_proto_list_len = s->ctx->alpn_client_proto_list_len;
371     }
372 #endif
373
374     s->verify_result = X509_V_OK;
375
376     s->method = ctx->method;
377
378     if (!s->method->ssl_new(s))
379         goto err;
380
381     s->references = 1;
382     s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
383
384     if(!SSL_clear(s))
385         goto err;
386
387     CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
388
389 #ifndef OPENSSL_NO_PSK
390     s->psk_client_callback = ctx->psk_client_callback;
391     s->psk_server_callback = ctx->psk_server_callback;
392 #endif
393
394     return (s);
395  err:
396     if (s != NULL)
397         SSL_free(s);
398     SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
399     return (NULL);
400 }
401
402 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
403                                    unsigned int sid_ctx_len)
404 {
405     if (sid_ctx_len > sizeof ctx->sid_ctx) {
406         SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
407                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
408         return 0;
409     }
410     ctx->sid_ctx_length = sid_ctx_len;
411     memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
412
413     return 1;
414 }
415
416 int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
417                                unsigned int sid_ctx_len)
418 {
419     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
420         SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
421                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
422         return 0;
423     }
424     ssl->sid_ctx_length = sid_ctx_len;
425     memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
426
427     return 1;
428 }
429
430 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
431 {
432     CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
433     ctx->generate_session_id = cb;
434     CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
435     return 1;
436 }
437
438 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
439 {
440     CRYPTO_w_lock(CRYPTO_LOCK_SSL);
441     ssl->generate_session_id = cb;
442     CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
443     return 1;
444 }
445
446 int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
447                                 unsigned int id_len)
448 {
449     /*
450      * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
451      * we can "construct" a session to give us the desired check - ie. to
452      * find if there's a session in the hash table that would conflict with
453      * any new session built out of this id/id_len and the ssl_version in use
454      * by this SSL.
455      */
456     SSL_SESSION r, *p;
457
458     if (id_len > sizeof r.session_id)
459         return 0;
460
461     r.ssl_version = ssl->version;
462     r.session_id_length = id_len;
463     memcpy(r.session_id, id, id_len);
464
465     CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
466     p = lh_SSL_SESSION_retrieve(ssl->ctx->sessions, &r);
467     CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
468     return (p != NULL);
469 }
470
471 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
472 {
473     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
474 }
475
476 int SSL_set_purpose(SSL *s, int purpose)
477 {
478     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
479 }
480
481 int SSL_CTX_set_trust(SSL_CTX *s, int trust)
482 {
483     return X509_VERIFY_PARAM_set_trust(s->param, trust);
484 }
485
486 int SSL_set_trust(SSL *s, int trust)
487 {
488     return X509_VERIFY_PARAM_set_trust(s->param, trust);
489 }
490
491 int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
492 {
493     return X509_VERIFY_PARAM_set1(ctx->param, vpm);
494 }
495
496 int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
497 {
498     return X509_VERIFY_PARAM_set1(ssl->param, vpm);
499 }
500
501 X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx)
502 {
503     return ctx->param;
504 }
505
506 X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)
507 {
508     return ssl->param;
509 }
510
511 void SSL_certs_clear(SSL *s)
512 {
513     ssl_cert_clear_certs(s->cert);
514 }
515
516 void SSL_free(SSL *s)
517 {
518     int i;
519
520     if (s == NULL)
521         return;
522
523     i = CRYPTO_add(&s->references, -1, CRYPTO_LOCK_SSL);
524 #ifdef REF_PRINT
525     REF_PRINT("SSL", s);
526 #endif
527     if (i > 0)
528         return;
529 #ifdef REF_CHECK
530     if (i < 0) {
531         fprintf(stderr, "SSL_free, bad reference count\n");
532         abort();                /* ok */
533     }
534 #endif
535
536     if (s->param)
537         X509_VERIFY_PARAM_free(s->param);
538
539     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
540
541     if (s->bbio != NULL) {
542         /* If the buffering BIO is in place, pop it off */
543         if (s->bbio == s->wbio) {
544             s->wbio = BIO_pop(s->wbio);
545         }
546         BIO_free(s->bbio);
547         s->bbio = NULL;
548     }
549     BIO_free_all(s->rbio);
550     if (s->wbio != s->rbio)
551         BIO_free_all(s->wbio);
552
553     if (s->init_buf != NULL)
554         BUF_MEM_free(s->init_buf);
555
556     /* add extra stuff */
557     if (s->cipher_list != NULL)
558         sk_SSL_CIPHER_free(s->cipher_list);
559     if (s->cipher_list_by_id != NULL)
560         sk_SSL_CIPHER_free(s->cipher_list_by_id);
561
562     /* Make the next call work :-) */
563     if (s->session != NULL) {
564         ssl_clear_bad_session(s);
565         SSL_SESSION_free(s->session);
566     }
567
568     ssl_clear_cipher_ctx(s);
569     ssl_clear_hash_ctx(&s->read_hash);
570     ssl_clear_hash_ctx(&s->write_hash);
571
572     if (s->cert != NULL)
573         ssl_cert_free(s->cert);
574     /* Free up if allocated */
575
576 #ifndef OPENSSL_NO_TLSEXT
577     if (s->tlsext_hostname)
578         OPENSSL_free(s->tlsext_hostname);
579     if (s->initial_ctx)
580         SSL_CTX_free(s->initial_ctx);
581 # ifndef OPENSSL_NO_EC
582     if (s->tlsext_ecpointformatlist)
583         OPENSSL_free(s->tlsext_ecpointformatlist);
584     if (s->tlsext_ellipticcurvelist)
585         OPENSSL_free(s->tlsext_ellipticcurvelist);
586 # endif                         /* OPENSSL_NO_EC */
587     if (s->tlsext_ocsp_exts)
588         sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free);
589     if (s->tlsext_ocsp_ids)
590         sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free);
591     if (s->tlsext_ocsp_resp)
592         OPENSSL_free(s->tlsext_ocsp_resp);
593     if (s->alpn_client_proto_list)
594         OPENSSL_free(s->alpn_client_proto_list);
595 #endif
596
597     if (s->client_CA != NULL)
598         sk_X509_NAME_pop_free(s->client_CA, X509_NAME_free);
599
600     if (s->method != NULL)
601         s->method->ssl_free(s);
602
603     RECORD_LAYER_release(&s->rlayer);
604
605     if (s->ctx)
606         SSL_CTX_free(s->ctx);
607
608 #ifndef OPENSSL_NO_KRB5
609     if (s->kssl_ctx != NULL)
610         kssl_ctx_free(s->kssl_ctx);
611 #endif                          /* OPENSSL_NO_KRB5 */
612
613 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
614     if (s->next_proto_negotiated)
615         OPENSSL_free(s->next_proto_negotiated);
616 #endif
617
618 #ifndef OPENSSL_NO_SRTP
619     if (s->srtp_profiles)
620         sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
621 #endif
622
623     OPENSSL_free(s);
624 }
625
626 void SSL_set_rbio(SSL *s, BIO *rbio)
627 {
628     if (s->rbio != rbio)
629         BIO_free_all(s->rbio);
630     s->rbio = rbio;
631 }
632
633 void SSL_set_wbio(SSL *s, BIO *wbio)
634 {
635     /*
636      * If the output buffering BIO is still in place, remove it
637      */
638     if (s->bbio != NULL) {
639         if (s->wbio == s->bbio) {
640             s->wbio = s->wbio->next_bio;
641             s->bbio->next_bio = NULL;
642         }
643     }
644     if (s->wbio != wbio && s->rbio != s->wbio)
645         BIO_free_all(s->wbio);
646     s->wbio = wbio;
647 }
648
649 void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
650 {
651     SSL_set_wbio(s, wbio);
652     SSL_set_rbio(s, rbio);
653 }
654
655 BIO *SSL_get_rbio(const SSL *s)
656 {
657     return (s->rbio);
658 }
659
660 BIO *SSL_get_wbio(const SSL *s)
661 {
662     return (s->wbio);
663 }
664
665 int SSL_get_fd(const SSL *s)
666 {
667     return (SSL_get_rfd(s));
668 }
669
670 int SSL_get_rfd(const SSL *s)
671 {
672     int ret = -1;
673     BIO *b, *r;
674
675     b = SSL_get_rbio(s);
676     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
677     if (r != NULL)
678         BIO_get_fd(r, &ret);
679     return (ret);
680 }
681
682 int SSL_get_wfd(const SSL *s)
683 {
684     int ret = -1;
685     BIO *b, *r;
686
687     b = SSL_get_wbio(s);
688     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
689     if (r != NULL)
690         BIO_get_fd(r, &ret);
691     return (ret);
692 }
693
694 #ifndef OPENSSL_NO_SOCK
695 int SSL_set_fd(SSL *s, int fd)
696 {
697     int ret = 0;
698     BIO *bio = NULL;
699
700     bio = BIO_new(BIO_s_socket());
701
702     if (bio == NULL) {
703         SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
704         goto err;
705     }
706     BIO_set_fd(bio, fd, BIO_NOCLOSE);
707     SSL_set_bio(s, bio, bio);
708     ret = 1;
709  err:
710     return (ret);
711 }
712
713 int SSL_set_wfd(SSL *s, int fd)
714 {
715     int ret = 0;
716     BIO *bio = NULL;
717
718     if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET)
719         || ((int)BIO_get_fd(s->rbio, NULL) != fd)) {
720         bio = BIO_new(BIO_s_socket());
721
722         if (bio == NULL) {
723             SSLerr(SSL_F_SSL_SET_WFD, ERR_R_BUF_LIB);
724             goto err;
725         }
726         BIO_set_fd(bio, fd, BIO_NOCLOSE);
727         SSL_set_bio(s, SSL_get_rbio(s), bio);
728     } else
729         SSL_set_bio(s, SSL_get_rbio(s), SSL_get_rbio(s));
730     ret = 1;
731  err:
732     return (ret);
733 }
734
735 int SSL_set_rfd(SSL *s, int fd)
736 {
737     int ret = 0;
738     BIO *bio = NULL;
739
740     if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET)
741         || ((int)BIO_get_fd(s->wbio, NULL) != fd)) {
742         bio = BIO_new(BIO_s_socket());
743
744         if (bio == NULL) {
745             SSLerr(SSL_F_SSL_SET_RFD, ERR_R_BUF_LIB);
746             goto err;
747         }
748         BIO_set_fd(bio, fd, BIO_NOCLOSE);
749         SSL_set_bio(s, bio, SSL_get_wbio(s));
750     } else
751         SSL_set_bio(s, SSL_get_wbio(s), SSL_get_wbio(s));
752     ret = 1;
753  err:
754     return (ret);
755 }
756 #endif
757
758 /* return length of latest Finished message we sent, copy to 'buf' */
759 size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
760 {
761     size_t ret = 0;
762
763     if (s->s3 != NULL) {
764         ret = s->s3->tmp.finish_md_len;
765         if (count > ret)
766             count = ret;
767         memcpy(buf, s->s3->tmp.finish_md, count);
768     }
769     return ret;
770 }
771
772 /* return length of latest Finished message we expected, copy to 'buf' */
773 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
774 {
775     size_t ret = 0;
776
777     if (s->s3 != NULL) {
778         ret = s->s3->tmp.peer_finish_md_len;
779         if (count > ret)
780             count = ret;
781         memcpy(buf, s->s3->tmp.peer_finish_md, count);
782     }
783     return ret;
784 }
785
786 int SSL_get_verify_mode(const SSL *s)
787 {
788     return (s->verify_mode);
789 }
790
791 int SSL_get_verify_depth(const SSL *s)
792 {
793     return X509_VERIFY_PARAM_get_depth(s->param);
794 }
795
796 int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *) {
797     return (s->verify_callback);
798 }
799
800 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
801 {
802     return (ctx->verify_mode);
803 }
804
805 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
806 {
807     return X509_VERIFY_PARAM_get_depth(ctx->param);
808 }
809
810 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int, X509_STORE_CTX *) {
811     return (ctx->default_verify_callback);
812 }
813
814 void SSL_set_verify(SSL *s, int mode,
815                     int (*callback) (int ok, X509_STORE_CTX *ctx))
816 {
817     s->verify_mode = mode;
818     if (callback != NULL)
819         s->verify_callback = callback;
820 }
821
822 void SSL_set_verify_depth(SSL *s, int depth)
823 {
824     X509_VERIFY_PARAM_set_depth(s->param, depth);
825 }
826
827 void SSL_set_read_ahead(SSL *s, int yes)
828 {
829     RECORD_LAYER_set_read_ahead(&s->rlayer, yes);
830 }
831
832 int SSL_get_read_ahead(const SSL *s)
833 {
834     return RECORD_LAYER_get_read_ahead(&s->rlayer);
835 }
836
837 int SSL_pending(const SSL *s)
838 {
839     /*
840      * SSL_pending cannot work properly if read-ahead is enabled
841      * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
842      * impossible to fix since SSL_pending cannot report errors that may be
843      * observed while scanning the new data. (Note that SSL_pending() is
844      * often used as a boolean value, so we'd better not return -1.)
845      */
846     return (s->method->ssl_pending(s));
847 }
848
849 X509 *SSL_get_peer_certificate(const SSL *s)
850 {
851     X509 *r;
852
853     if ((s == NULL) || (s->session == NULL))
854         r = NULL;
855     else
856         r = s->session->peer;
857
858     if (r == NULL)
859         return (r);
860
861     CRYPTO_add(&r->references, 1, CRYPTO_LOCK_X509);
862
863     return (r);
864 }
865
866 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
867 {
868     STACK_OF(X509) *r;
869
870     if ((s == NULL) || (s->session == NULL)
871         || (s->session->sess_cert == NULL))
872         r = NULL;
873     else
874         r = s->session->sess_cert->cert_chain;
875
876     /*
877      * If we are a client, cert_chain includes the peer's own certificate; if
878      * we are a server, it does not.
879      */
880
881     return (r);
882 }
883
884 /*
885  * Now in theory, since the calling process own 't' it should be safe to
886  * modify.  We need to be able to read f without being hassled
887  */
888 int SSL_copy_session_id(SSL *t, const SSL *f)
889 {
890     /* Do we need to to SSL locking? */
891     if(!SSL_set_session(t, SSL_get_session(f))) {
892         return 0;
893     }
894
895     /*
896      * what if we are setup as SSLv2 but want to talk SSLv3 or vice-versa
897      */
898     if (t->method != f->method) {
899         t->method->ssl_free(t); /* cleanup current */
900         t->method = f->method;  /* change method */
901         t->method->ssl_new(t);  /* setup new */
902     }
903
904     CRYPTO_add(&f->cert->references, 1, CRYPTO_LOCK_SSL_CERT);
905     ssl_cert_free(t->cert);
906     t->cert = f->cert;
907     if(!SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length)) {
908         return 0;
909     }
910
911     return 1;
912 }
913
914 /* Fix this so it checks all the valid key/cert options */
915 int SSL_CTX_check_private_key(const SSL_CTX *ctx)
916 {
917     if ((ctx == NULL) ||
918         (ctx->cert->key->x509 == NULL)) {
919         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
920                SSL_R_NO_CERTIFICATE_ASSIGNED);
921         return (0);
922     }
923     if (ctx->cert->key->privatekey == NULL) {
924         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
925                SSL_R_NO_PRIVATE_KEY_ASSIGNED);
926         return (0);
927     }
928     return (X509_check_private_key
929             (ctx->cert->key->x509, ctx->cert->key->privatekey));
930 }
931
932 /* Fix this function so that it takes an optional type parameter */
933 int SSL_check_private_key(const SSL *ssl)
934 {
935     if (ssl == NULL) {
936         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
937         return (0);
938     }
939     if (ssl->cert->key->x509 == NULL) {
940         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
941         return (0);
942     }
943     if (ssl->cert->key->privatekey == NULL) {
944         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
945         return (0);
946     }
947     return (X509_check_private_key(ssl->cert->key->x509,
948                                    ssl->cert->key->privatekey));
949 }
950
951 int SSL_accept(SSL *s)
952 {
953     if (s->handshake_func == 0)
954         /* Not properly initialized yet */
955         SSL_set_accept_state(s);
956
957     return (s->method->ssl_accept(s));
958 }
959
960 int SSL_connect(SSL *s)
961 {
962     if (s->handshake_func == 0)
963         /* Not properly initialized yet */
964         SSL_set_connect_state(s);
965
966     return (s->method->ssl_connect(s));
967 }
968
969 long SSL_get_default_timeout(const SSL *s)
970 {
971     return (s->method->get_timeout());
972 }
973
974 int SSL_read(SSL *s, void *buf, int num)
975 {
976     if (s->handshake_func == 0) {
977         SSLerr(SSL_F_SSL_READ, SSL_R_UNINITIALIZED);
978         return -1;
979     }
980
981     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
982         s->rwstate = SSL_NOTHING;
983         return (0);
984     }
985     return (s->method->ssl_read(s, buf, num));
986 }
987
988 int SSL_peek(SSL *s, void *buf, int num)
989 {
990     if (s->handshake_func == 0) {
991         SSLerr(SSL_F_SSL_PEEK, SSL_R_UNINITIALIZED);
992         return -1;
993     }
994
995     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
996         return (0);
997     }
998     return (s->method->ssl_peek(s, buf, num));
999 }
1000
1001 int SSL_write(SSL *s, const void *buf, int num)
1002 {
1003     if (s->handshake_func == 0) {
1004         SSLerr(SSL_F_SSL_WRITE, SSL_R_UNINITIALIZED);
1005         return -1;
1006     }
1007
1008     if (s->shutdown & SSL_SENT_SHUTDOWN) {
1009         s->rwstate = SSL_NOTHING;
1010         SSLerr(SSL_F_SSL_WRITE, SSL_R_PROTOCOL_IS_SHUTDOWN);
1011         return (-1);
1012     }
1013     return (s->method->ssl_write(s, buf, num));
1014 }
1015
1016 int SSL_shutdown(SSL *s)
1017 {
1018     /*
1019      * Note that this function behaves differently from what one might
1020      * expect.  Return values are 0 for no success (yet), 1 for success; but
1021      * calling it once is usually not enough, even if blocking I/O is used
1022      * (see ssl3_shutdown).
1023      */
1024
1025     if (s->handshake_func == 0) {
1026         SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED);
1027         return -1;
1028     }
1029
1030     if ((s != NULL) && !SSL_in_init(s))
1031         return (s->method->ssl_shutdown(s));
1032     else
1033         return (1);
1034 }
1035
1036 int SSL_renegotiate(SSL *s)
1037 {
1038     if (s->renegotiate == 0)
1039         s->renegotiate = 1;
1040
1041     s->new_session = 1;
1042
1043     return (s->method->ssl_renegotiate(s));
1044 }
1045
1046 int SSL_renegotiate_abbreviated(SSL *s)
1047 {
1048     if (s->renegotiate == 0)
1049         s->renegotiate = 1;
1050
1051     s->new_session = 0;
1052
1053     return (s->method->ssl_renegotiate(s));
1054 }
1055
1056 int SSL_renegotiate_pending(SSL *s)
1057 {
1058     /*
1059      * becomes true when negotiation is requested; false again once a
1060      * handshake has finished
1061      */
1062     return (s->renegotiate != 0);
1063 }
1064
1065 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
1066 {
1067     long l;
1068
1069     switch (cmd) {
1070     case SSL_CTRL_GET_READ_AHEAD:
1071         return (RECORD_LAYER_get_read_ahead(&s->rlayer));
1072     case SSL_CTRL_SET_READ_AHEAD:
1073         l = RECORD_LAYER_get_read_ahead(&s->rlayer);
1074         RECORD_LAYER_set_read_ahead(&s->rlayer, larg);
1075         return (l);
1076
1077     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1078         s->msg_callback_arg = parg;
1079         return 1;
1080
1081     case SSL_CTRL_OPTIONS:
1082         return (s->options |= larg);
1083     case SSL_CTRL_CLEAR_OPTIONS:
1084         return (s->options &= ~larg);
1085     case SSL_CTRL_MODE:
1086         return (s->mode |= larg);
1087     case SSL_CTRL_CLEAR_MODE:
1088         return (s->mode &= ~larg);
1089     case SSL_CTRL_GET_MAX_CERT_LIST:
1090         return (s->max_cert_list);
1091     case SSL_CTRL_SET_MAX_CERT_LIST:
1092         l = s->max_cert_list;
1093         s->max_cert_list = larg;
1094         return (l);
1095     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1096         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1097             return 0;
1098         s->max_send_fragment = larg;
1099         return 1;
1100     case SSL_CTRL_GET_RI_SUPPORT:
1101         if (s->s3)
1102             return s->s3->send_connection_binding;
1103         else
1104             return 0;
1105     case SSL_CTRL_CERT_FLAGS:
1106         return (s->cert->cert_flags |= larg);
1107     case SSL_CTRL_CLEAR_CERT_FLAGS:
1108         return (s->cert->cert_flags &= ~larg);
1109
1110     case SSL_CTRL_GET_RAW_CIPHERLIST:
1111         if (parg) {
1112             if (s->cert->ciphers_raw == NULL)
1113                 return 0;
1114             *(unsigned char **)parg = s->cert->ciphers_raw;
1115             return (int)s->cert->ciphers_rawlen;
1116         } else
1117             return ssl_put_cipher_by_char(s, NULL, NULL);
1118     case SSL_CTRL_GET_EXTMS_SUPPORT:
1119         if (!s->session || SSL_in_init(s) || s->in_handshake)
1120                 return -1;
1121         if (s->session->flags & SSL_SESS_FLAG_EXTMS)
1122             return 1;
1123         else
1124             return 0;
1125     default:
1126         return (s->method->ssl_ctrl(s, cmd, larg, parg));
1127     }
1128 }
1129
1130 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
1131 {
1132     switch (cmd) {
1133     case SSL_CTRL_SET_MSG_CALLBACK:
1134         s->msg_callback = (void (*)
1135                            (int write_p, int version, int content_type,
1136                             const void *buf, size_t len, SSL *ssl,
1137                             void *arg))(fp);
1138         return 1;
1139
1140     default:
1141         return (s->method->ssl_callback_ctrl(s, cmd, fp));
1142     }
1143 }
1144
1145 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
1146 {
1147     return ctx->sessions;
1148 }
1149
1150 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
1151 {
1152     long l;
1153     /* For some cases with ctx == NULL perform syntax checks */
1154     if (ctx == NULL) {
1155         switch (cmd) {
1156 #ifndef OPENSSL_NO_EC
1157         case SSL_CTRL_SET_CURVES_LIST:
1158             return tls1_set_curves_list(NULL, NULL, parg);
1159 #endif
1160         case SSL_CTRL_SET_SIGALGS_LIST:
1161         case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
1162             return tls1_set_sigalgs_list(NULL, parg, 0);
1163         default:
1164             return 0;
1165         }
1166     }
1167
1168     switch (cmd) {
1169     case SSL_CTRL_GET_READ_AHEAD:
1170         return (ctx->read_ahead);
1171     case SSL_CTRL_SET_READ_AHEAD:
1172         l = ctx->read_ahead;
1173         ctx->read_ahead = larg;
1174         return (l);
1175
1176     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1177         ctx->msg_callback_arg = parg;
1178         return 1;
1179
1180     case SSL_CTRL_GET_MAX_CERT_LIST:
1181         return (ctx->max_cert_list);
1182     case SSL_CTRL_SET_MAX_CERT_LIST:
1183         l = ctx->max_cert_list;
1184         ctx->max_cert_list = larg;
1185         return (l);
1186
1187     case SSL_CTRL_SET_SESS_CACHE_SIZE:
1188         l = ctx->session_cache_size;
1189         ctx->session_cache_size = larg;
1190         return (l);
1191     case SSL_CTRL_GET_SESS_CACHE_SIZE:
1192         return (ctx->session_cache_size);
1193     case SSL_CTRL_SET_SESS_CACHE_MODE:
1194         l = ctx->session_cache_mode;
1195         ctx->session_cache_mode = larg;
1196         return (l);
1197     case SSL_CTRL_GET_SESS_CACHE_MODE:
1198         return (ctx->session_cache_mode);
1199
1200     case SSL_CTRL_SESS_NUMBER:
1201         return (lh_SSL_SESSION_num_items(ctx->sessions));
1202     case SSL_CTRL_SESS_CONNECT:
1203         return (ctx->stats.sess_connect);
1204     case SSL_CTRL_SESS_CONNECT_GOOD:
1205         return (ctx->stats.sess_connect_good);
1206     case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
1207         return (ctx->stats.sess_connect_renegotiate);
1208     case SSL_CTRL_SESS_ACCEPT:
1209         return (ctx->stats.sess_accept);
1210     case SSL_CTRL_SESS_ACCEPT_GOOD:
1211         return (ctx->stats.sess_accept_good);
1212     case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
1213         return (ctx->stats.sess_accept_renegotiate);
1214     case SSL_CTRL_SESS_HIT:
1215         return (ctx->stats.sess_hit);
1216     case SSL_CTRL_SESS_CB_HIT:
1217         return (ctx->stats.sess_cb_hit);
1218     case SSL_CTRL_SESS_MISSES:
1219         return (ctx->stats.sess_miss);
1220     case SSL_CTRL_SESS_TIMEOUTS:
1221         return (ctx->stats.sess_timeout);
1222     case SSL_CTRL_SESS_CACHE_FULL:
1223         return (ctx->stats.sess_cache_full);
1224     case SSL_CTRL_OPTIONS:
1225         return (ctx->options |= larg);
1226     case SSL_CTRL_CLEAR_OPTIONS:
1227         return (ctx->options &= ~larg);
1228     case SSL_CTRL_MODE:
1229         return (ctx->mode |= larg);
1230     case SSL_CTRL_CLEAR_MODE:
1231         return (ctx->mode &= ~larg);
1232     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1233         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1234             return 0;
1235         ctx->max_send_fragment = larg;
1236         return 1;
1237     case SSL_CTRL_CERT_FLAGS:
1238         return (ctx->cert->cert_flags |= larg);
1239     case SSL_CTRL_CLEAR_CERT_FLAGS:
1240         return (ctx->cert->cert_flags &= ~larg);
1241     default:
1242         return (ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg));
1243     }
1244 }
1245
1246 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
1247 {
1248     switch (cmd) {
1249     case SSL_CTRL_SET_MSG_CALLBACK:
1250         ctx->msg_callback = (void (*)
1251                              (int write_p, int version, int content_type,
1252                               const void *buf, size_t len, SSL *ssl,
1253                               void *arg))(fp);
1254         return 1;
1255
1256     default:
1257         return (ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp));
1258     }
1259 }
1260
1261 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
1262 {
1263     long l;
1264
1265     l = a->id - b->id;
1266     if (l == 0L)
1267         return (0);
1268     else
1269         return ((l > 0) ? 1 : -1);
1270 }
1271
1272 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
1273                           const SSL_CIPHER *const *bp)
1274 {
1275     long l;
1276
1277     l = (*ap)->id - (*bp)->id;
1278     if (l == 0L)
1279         return (0);
1280     else
1281         return ((l > 0) ? 1 : -1);
1282 }
1283
1284 /** return a STACK of the ciphers available for the SSL and in order of
1285  * preference */
1286 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
1287 {
1288     if (s != NULL) {
1289         if (s->cipher_list != NULL) {
1290             return (s->cipher_list);
1291         } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
1292             return (s->ctx->cipher_list);
1293         }
1294     }
1295     return (NULL);
1296 }
1297
1298 STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
1299 {
1300     STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
1301     int i;
1302     ciphers = SSL_get_ciphers(s);
1303     if (!ciphers)
1304         return NULL;
1305     ssl_set_client_disabled(s);
1306     for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1307         const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
1308         if (!ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED)) {
1309             if (!sk)
1310                 sk = sk_SSL_CIPHER_new_null();
1311             if (!sk)
1312                 return NULL;
1313             if (!sk_SSL_CIPHER_push(sk, c)) {
1314                 sk_SSL_CIPHER_free(sk);
1315                 return NULL;
1316             }
1317         }
1318     }
1319     return sk;
1320 }
1321
1322 /** return a STACK of the ciphers available for the SSL and in order of
1323  * algorithm id */
1324 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
1325 {
1326     if (s != NULL) {
1327         if (s->cipher_list_by_id != NULL) {
1328             return (s->cipher_list_by_id);
1329         } else if ((s->ctx != NULL) && (s->ctx->cipher_list_by_id != NULL)) {
1330             return (s->ctx->cipher_list_by_id);
1331         }
1332     }
1333     return (NULL);
1334 }
1335
1336 /** The old interface to get the same thing as SSL_get_ciphers() */
1337 const char *SSL_get_cipher_list(const SSL *s, int n)
1338 {
1339     SSL_CIPHER *c;
1340     STACK_OF(SSL_CIPHER) *sk;
1341
1342     if (s == NULL)
1343         return (NULL);
1344     sk = SSL_get_ciphers(s);
1345     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
1346         return (NULL);
1347     c = sk_SSL_CIPHER_value(sk, n);
1348     if (c == NULL)
1349         return (NULL);
1350     return (c->name);
1351 }
1352
1353 /** specify the ciphers to be used by default by the SSL_CTX */
1354 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
1355 {
1356     STACK_OF(SSL_CIPHER) *sk;
1357
1358     sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
1359                                 &ctx->cipher_list_by_id, str, ctx->cert);
1360     /*
1361      * ssl_create_cipher_list may return an empty stack if it was unable to
1362      * find a cipher matching the given rule string (for example if the rule
1363      * string specifies a cipher which has been disabled). This is not an
1364      * error as far as ssl_create_cipher_list is concerned, and hence
1365      * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
1366      */
1367     if (sk == NULL)
1368         return 0;
1369     else if (sk_SSL_CIPHER_num(sk) == 0) {
1370         SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
1371         return 0;
1372     }
1373     return 1;
1374 }
1375
1376 /** specify the ciphers to be used by the SSL */
1377 int SSL_set_cipher_list(SSL *s, const char *str)
1378 {
1379     STACK_OF(SSL_CIPHER) *sk;
1380
1381     sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
1382                                 &s->cipher_list_by_id, str, s->cert);
1383     /* see comment in SSL_CTX_set_cipher_list */
1384     if (sk == NULL)
1385         return 0;
1386     else if (sk_SSL_CIPHER_num(sk) == 0) {
1387         SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
1388         return 0;
1389     }
1390     return 1;
1391 }
1392
1393 /* works well for SSLv2, not so good for SSLv3 */
1394 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
1395 {
1396     char *p;
1397     STACK_OF(SSL_CIPHER) *sk;
1398     SSL_CIPHER *c;
1399     int i;
1400
1401     if ((s->session == NULL) || (s->session->ciphers == NULL) || (len < 2))
1402         return (NULL);
1403
1404     p = buf;
1405     sk = s->session->ciphers;
1406
1407     if (sk_SSL_CIPHER_num(sk) == 0)
1408         return NULL;
1409
1410     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1411         int n;
1412
1413         c = sk_SSL_CIPHER_value(sk, i);
1414         n = strlen(c->name);
1415         if (n + 1 > len) {
1416             if (p != buf)
1417                 --p;
1418             *p = '\0';
1419             return buf;
1420         }
1421         strcpy(p, c->name);
1422         p += n;
1423         *(p++) = ':';
1424         len -= n + 1;
1425     }
1426     p[-1] = '\0';
1427     return (buf);
1428 }
1429
1430 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
1431                              unsigned char *p,
1432                              int (*put_cb) (const SSL_CIPHER *,
1433                                             unsigned char *))
1434 {
1435     int i, j = 0;
1436     SSL_CIPHER *c;
1437     unsigned char *q;
1438     int empty_reneg_info_scsv = !s->renegotiate;
1439     /* Set disabled masks for this session */
1440     ssl_set_client_disabled(s);
1441
1442     if (sk == NULL)
1443         return (0);
1444     q = p;
1445     if (put_cb == NULL)
1446         put_cb = s->method->put_cipher_by_char;
1447
1448     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1449         c = sk_SSL_CIPHER_value(sk, i);
1450         /* Skip disabled ciphers */
1451         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
1452             continue;
1453 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
1454         if (c->id == SSL3_CK_SCSV) {
1455             if (!empty_reneg_info_scsv)
1456                 continue;
1457             else
1458                 empty_reneg_info_scsv = 0;
1459         }
1460 #endif
1461         j = put_cb(c, p);
1462         p += j;
1463     }
1464     /*
1465      * If p == q, no ciphers; caller indicates an error. Otherwise, add
1466      * applicable SCSVs.
1467      */
1468     if (p != q) {
1469         if (empty_reneg_info_scsv) {
1470             static SSL_CIPHER scsv = {
1471                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
1472             };
1473             j = put_cb(&scsv, p);
1474             p += j;
1475 #ifdef OPENSSL_RI_DEBUG
1476             fprintf(stderr,
1477                     "TLS_EMPTY_RENEGOTIATION_INFO_SCSV sent by client\n");
1478 #endif
1479         }
1480         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
1481             static SSL_CIPHER scsv = {
1482                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
1483             };
1484             j = put_cb(&scsv, p);
1485             p += j;
1486         }
1487     }
1488
1489     return (p - q);
1490 }
1491
1492 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, unsigned char *p,
1493                                                int num,
1494                                                STACK_OF(SSL_CIPHER) **skp)
1495 {
1496     const SSL_CIPHER *c;
1497     STACK_OF(SSL_CIPHER) *sk;
1498     int i, n;
1499
1500     if (s->s3)
1501         s->s3->send_connection_binding = 0;
1502
1503     n = ssl_put_cipher_by_char(s, NULL, NULL);
1504     if (n == 0 || (num % n) != 0) {
1505         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
1506                SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
1507         return (NULL);
1508     }
1509     if ((skp == NULL) || (*skp == NULL))
1510         sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
1511     else {
1512         sk = *skp;
1513         sk_SSL_CIPHER_zero(sk);
1514     }
1515
1516     if (s->cert->ciphers_raw)
1517         OPENSSL_free(s->cert->ciphers_raw);
1518     s->cert->ciphers_raw = BUF_memdup(p, num);
1519     if (s->cert->ciphers_raw == NULL) {
1520         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
1521         goto err;
1522     }
1523     s->cert->ciphers_rawlen = (size_t)num;
1524
1525     for (i = 0; i < num; i += n) {
1526         /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
1527         if (s->s3 && (n != 3 || !p[0]) &&
1528             (p[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
1529             (p[n - 1] == (SSL3_CK_SCSV & 0xff))) {
1530             /* SCSV fatal if renegotiating */
1531             if (s->renegotiate) {
1532                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
1533                        SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1534                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1535                 goto err;
1536             }
1537             s->s3->send_connection_binding = 1;
1538             p += n;
1539 #ifdef OPENSSL_RI_DEBUG
1540             fprintf(stderr, "SCSV received by server\n");
1541 #endif
1542             continue;
1543         }
1544
1545         /* Check for TLS_FALLBACK_SCSV */
1546         if ((n != 3 || !p[0]) &&
1547             (p[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
1548             (p[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
1549             /*
1550              * The SCSV indicates that the client previously tried a higher
1551              * version. Fail if the current version is an unexpected
1552              * downgrade.
1553              */
1554             if (!SSL_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, 0, NULL)) {
1555                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
1556                        SSL_R_INAPPROPRIATE_FALLBACK);
1557                 if (s->s3)
1558                     ssl3_send_alert(s, SSL3_AL_FATAL,
1559                                     SSL_AD_INAPPROPRIATE_FALLBACK);
1560                 goto err;
1561             }
1562             p += n;
1563             continue;
1564         }
1565
1566         c = ssl_get_cipher_by_char(s, p);
1567         p += n;
1568         if (c != NULL) {
1569             if (!sk_SSL_CIPHER_push(sk, c)) {
1570                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
1571                 goto err;
1572             }
1573         }
1574     }
1575
1576     if (skp != NULL)
1577         *skp = sk;
1578     return (sk);
1579  err:
1580     if ((skp == NULL) || (*skp == NULL))
1581         sk_SSL_CIPHER_free(sk);
1582     return (NULL);
1583 }
1584
1585 #ifndef OPENSSL_NO_TLSEXT
1586 /** return a servername extension value if provided in Client Hello, or NULL.
1587  * So far, only host_name types are defined (RFC 3546).
1588  */
1589
1590 const char *SSL_get_servername(const SSL *s, const int type)
1591 {
1592     if (type != TLSEXT_NAMETYPE_host_name)
1593         return NULL;
1594
1595     return s->session && !s->tlsext_hostname ?
1596         s->session->tlsext_hostname : s->tlsext_hostname;
1597 }
1598
1599 int SSL_get_servername_type(const SSL *s)
1600 {
1601     if (s->session
1602         && (!s->tlsext_hostname ? s->session->
1603             tlsext_hostname : s->tlsext_hostname))
1604         return TLSEXT_NAMETYPE_host_name;
1605     return -1;
1606 }
1607
1608 /*
1609  * SSL_select_next_proto implements the standard protocol selection. It is
1610  * expected that this function is called from the callback set by
1611  * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
1612  * vector of 8-bit, length prefixed byte strings. The length byte itself is
1613  * not included in the length. A byte string of length 0 is invalid. No byte
1614  * string may be truncated. The current, but experimental algorithm for
1615  * selecting the protocol is: 1) If the server doesn't support NPN then this
1616  * is indicated to the callback. In this case, the client application has to
1617  * abort the connection or have a default application level protocol. 2) If
1618  * the server supports NPN, but advertises an empty list then the client
1619  * selects the first protcol in its list, but indicates via the API that this
1620  * fallback case was enacted. 3) Otherwise, the client finds the first
1621  * protocol in the server's list that it supports and selects this protocol.
1622  * This is because it's assumed that the server has better information about
1623  * which protocol a client should use. 4) If the client doesn't support any
1624  * of the server's advertised protocols, then this is treated the same as
1625  * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
1626  * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
1627  */
1628 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
1629                           const unsigned char *server,
1630                           unsigned int server_len,
1631                           const unsigned char *client,
1632                           unsigned int client_len)
1633 {
1634     unsigned int i, j;
1635     const unsigned char *result;
1636     int status = OPENSSL_NPN_UNSUPPORTED;
1637
1638     /*
1639      * For each protocol in server preference order, see if we support it.
1640      */
1641     for (i = 0; i < server_len;) {
1642         for (j = 0; j < client_len;) {
1643             if (server[i] == client[j] &&
1644                 memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
1645                 /* We found a match */
1646                 result = &server[i];
1647                 status = OPENSSL_NPN_NEGOTIATED;
1648                 goto found;
1649             }
1650             j += client[j];
1651             j++;
1652         }
1653         i += server[i];
1654         i++;
1655     }
1656
1657     /* There's no overlap between our protocols and the server's list. */
1658     result = client;
1659     status = OPENSSL_NPN_NO_OVERLAP;
1660
1661  found:
1662     *out = (unsigned char *)result + 1;
1663     *outlen = result[0];
1664     return status;
1665 }
1666
1667 # ifndef OPENSSL_NO_NEXTPROTONEG
1668 /*
1669  * SSL_get0_next_proto_negotiated sets *data and *len to point to the
1670  * client's requested protocol for this connection and returns 0. If the
1671  * client didn't request any protocol, then *data is set to NULL. Note that
1672  * the client can request any protocol it chooses. The value returned from
1673  * this function need not be a member of the list of supported protocols
1674  * provided by the callback.
1675  */
1676 void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
1677                                     unsigned *len)
1678 {
1679     *data = s->next_proto_negotiated;
1680     if (!*data) {
1681         *len = 0;
1682     } else {
1683         *len = s->next_proto_negotiated_len;
1684     }
1685 }
1686
1687 /*
1688  * SSL_CTX_set_next_protos_advertised_cb sets a callback that is called when
1689  * a TLS server needs a list of supported protocols for Next Protocol
1690  * Negotiation. The returned list must be in wire format.  The list is
1691  * returned by setting |out| to point to it and |outlen| to its length. This
1692  * memory will not be modified, but one should assume that the SSL* keeps a
1693  * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
1694  * wishes to advertise. Otherwise, no such extension will be included in the
1695  * ServerHello.
1696  */
1697 void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx,
1698                                            int (*cb) (SSL *ssl,
1699                                                       const unsigned char
1700                                                       **out,
1701                                                       unsigned int *outlen,
1702                                                       void *arg), void *arg)
1703 {
1704     ctx->next_protos_advertised_cb = cb;
1705     ctx->next_protos_advertised_cb_arg = arg;
1706 }
1707
1708 /*
1709  * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
1710  * client needs to select a protocol from the server's provided list. |out|
1711  * must be set to point to the selected protocol (which may be within |in|).
1712  * The length of the protocol name must be written into |outlen|. The
1713  * server's advertised protocols are provided in |in| and |inlen|. The
1714  * callback can assume that |in| is syntactically valid. The client must
1715  * select a protocol. It is fatal to the connection if this callback returns
1716  * a value other than SSL_TLSEXT_ERR_OK.
1717  */
1718 void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx,
1719                                       int (*cb) (SSL *s, unsigned char **out,
1720                                                  unsigned char *outlen,
1721                                                  const unsigned char *in,
1722                                                  unsigned int inlen,
1723                                                  void *arg), void *arg)
1724 {
1725     ctx->next_proto_select_cb = cb;
1726     ctx->next_proto_select_cb_arg = arg;
1727 }
1728 # endif
1729
1730 /*
1731  * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
1732  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
1733  * length-prefixed strings). Returns 0 on success.
1734  */
1735 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
1736                             unsigned protos_len)
1737 {
1738     if (ctx->alpn_client_proto_list)
1739         OPENSSL_free(ctx->alpn_client_proto_list);
1740
1741     ctx->alpn_client_proto_list = OPENSSL_malloc(protos_len);
1742     if (!ctx->alpn_client_proto_list)
1743         return 1;
1744     memcpy(ctx->alpn_client_proto_list, protos, protos_len);
1745     ctx->alpn_client_proto_list_len = protos_len;
1746
1747     return 0;
1748 }
1749
1750 /*
1751  * SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
1752  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
1753  * length-prefixed strings). Returns 0 on success.
1754  */
1755 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
1756                         unsigned protos_len)
1757 {
1758     if (ssl->alpn_client_proto_list)
1759         OPENSSL_free(ssl->alpn_client_proto_list);
1760
1761     ssl->alpn_client_proto_list = OPENSSL_malloc(protos_len);
1762     if (!ssl->alpn_client_proto_list)
1763         return 1;
1764     memcpy(ssl->alpn_client_proto_list, protos, protos_len);
1765     ssl->alpn_client_proto_list_len = protos_len;
1766
1767     return 0;
1768 }
1769
1770 /*
1771  * SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
1772  * called during ClientHello processing in order to select an ALPN protocol
1773  * from the client's list of offered protocols.
1774  */
1775 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
1776                                 int (*cb) (SSL *ssl,
1777                                            const unsigned char **out,
1778                                            unsigned char *outlen,
1779                                            const unsigned char *in,
1780                                            unsigned int inlen,
1781                                            void *arg), void *arg)
1782 {
1783     ctx->alpn_select_cb = cb;
1784     ctx->alpn_select_cb_arg = arg;
1785 }
1786
1787 /*
1788  * SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from
1789  * |ssl|. On return it sets |*data| to point to |*len| bytes of protocol name
1790  * (not including the leading length-prefix byte). If the server didn't
1791  * respond with a negotiated protocol then |*len| will be zero.
1792  */
1793 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
1794                             unsigned *len)
1795 {
1796     *data = NULL;
1797     if (ssl->s3)
1798         *data = ssl->s3->alpn_selected;
1799     if (*data == NULL)
1800         *len = 0;
1801     else
1802         *len = ssl->s3->alpn_selected_len;
1803 }
1804
1805 #endif                          /* !OPENSSL_NO_TLSEXT */
1806
1807 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1808                                const char *label, size_t llen,
1809                                const unsigned char *p, size_t plen,
1810                                int use_context)
1811 {
1812     if (s->version < TLS1_VERSION)
1813         return -1;
1814
1815     return s->method->ssl3_enc->export_keying_material(s, out, olen, label,
1816                                                        llen, p, plen,
1817                                                        use_context);
1818 }
1819
1820 static unsigned long ssl_session_hash(const SSL_SESSION *a)
1821 {
1822     unsigned long l;
1823
1824     l = (unsigned long)
1825         ((unsigned int)a->session_id[0]) |
1826         ((unsigned int)a->session_id[1] << 8L) |
1827         ((unsigned long)a->session_id[2] << 16L) |
1828         ((unsigned long)a->session_id[3] << 24L);
1829     return (l);
1830 }
1831
1832 /*
1833  * NB: If this function (or indeed the hash function which uses a sort of
1834  * coarser function than this one) is changed, ensure
1835  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
1836  * being able to construct an SSL_SESSION that will collide with any existing
1837  * session with a matching session ID.
1838  */
1839 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
1840 {
1841     if (a->ssl_version != b->ssl_version)
1842         return (1);
1843     if (a->session_id_length != b->session_id_length)
1844         return (1);
1845     return (memcmp(a->session_id, b->session_id, a->session_id_length));
1846 }
1847
1848 /*
1849  * These wrapper functions should remain rather than redeclaring
1850  * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
1851  * variable. The reason is that the functions aren't static, they're exposed
1852  * via ssl.h.
1853  */
1854 static IMPLEMENT_LHASH_HASH_FN(ssl_session, SSL_SESSION)
1855 static IMPLEMENT_LHASH_COMP_FN(ssl_session, SSL_SESSION)
1856
1857 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
1858 {
1859     SSL_CTX *ret = NULL;
1860
1861     if (meth == NULL) {
1862         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_NULL_SSL_METHOD_PASSED);
1863         return (NULL);
1864     }
1865
1866     if (FIPS_mode() && (meth->version < TLS1_VERSION)) {
1867         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
1868         return NULL;
1869     }
1870
1871     if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
1872         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
1873         goto err;
1874     }
1875     ret = (SSL_CTX *)OPENSSL_malloc(sizeof(SSL_CTX));
1876     if (ret == NULL)
1877         goto err;
1878
1879     memset(ret, 0, sizeof(SSL_CTX));
1880
1881     ret->method = meth;
1882
1883     ret->cert_store = NULL;
1884     ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
1885     ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
1886     ret->session_cache_head = NULL;
1887     ret->session_cache_tail = NULL;
1888
1889     /* We take the system default */
1890     ret->session_timeout = meth->get_timeout();
1891
1892     ret->new_session_cb = 0;
1893     ret->remove_session_cb = 0;
1894     ret->get_session_cb = 0;
1895     ret->generate_session_id = 0;
1896
1897     memset((char *)&ret->stats, 0, sizeof(ret->stats));
1898
1899     ret->references = 1;
1900     ret->quiet_shutdown = 0;
1901     ret->info_callback = NULL;
1902     ret->app_verify_callback = 0;
1903     ret->app_verify_arg = NULL;
1904     ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
1905     ret->read_ahead = 0;
1906     ret->msg_callback = 0;
1907     ret->msg_callback_arg = NULL;
1908     ret->verify_mode = SSL_VERIFY_NONE;
1909     ret->sid_ctx_length = 0;
1910     ret->default_verify_callback = NULL;
1911     if ((ret->cert = ssl_cert_new()) == NULL)
1912         goto err;
1913
1914     ret->default_passwd_callback = 0;
1915     ret->default_passwd_callback_userdata = NULL;
1916     ret->client_cert_cb = 0;
1917     ret->app_gen_cookie_cb = 0;
1918     ret->app_verify_cookie_cb = 0;
1919
1920     ret->sessions = lh_SSL_SESSION_new();
1921     if (ret->sessions == NULL)
1922         goto err;
1923     ret->cert_store = X509_STORE_new();
1924     if (ret->cert_store == NULL)
1925         goto err;
1926
1927     if(!ssl_create_cipher_list(ret->method,
1928                            &ret->cipher_list, &ret->cipher_list_by_id,
1929                            SSL_DEFAULT_CIPHER_LIST, ret->cert)
1930        || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
1931         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_LIBRARY_HAS_NO_CIPHERS);
1932         goto err2;
1933     }
1934
1935     ret->param = X509_VERIFY_PARAM_new();
1936     if (!ret->param)
1937         goto err;
1938
1939     if ((ret->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
1940         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
1941         goto err2;
1942     }
1943     if ((ret->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
1944         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
1945         goto err2;
1946     }
1947
1948     if ((ret->client_CA = sk_X509_NAME_new_null()) == NULL)
1949         goto err;
1950
1951     CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data);
1952
1953     ret->extra_certs = NULL;
1954     /* No compression for DTLS */
1955     if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
1956         ret->comp_methods = SSL_COMP_get_compression_methods();
1957
1958     ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1959
1960 #ifndef OPENSSL_NO_TLSEXT
1961     ret->tlsext_servername_callback = 0;
1962     ret->tlsext_servername_arg = NULL;
1963     /* Setup RFC4507 ticket keys */
1964     if ((RAND_bytes(ret->tlsext_tick_key_name, 16) <= 0)
1965         || (RAND_bytes(ret->tlsext_tick_hmac_key, 16) <= 0)
1966         || (RAND_bytes(ret->tlsext_tick_aes_key, 16) <= 0))
1967         ret->options |= SSL_OP_NO_TICKET;
1968
1969     ret->tlsext_status_cb = 0;
1970     ret->tlsext_status_arg = NULL;
1971
1972 # ifndef OPENSSL_NO_NEXTPROTONEG
1973     ret->next_protos_advertised_cb = 0;
1974     ret->next_proto_select_cb = 0;
1975 # endif
1976 #endif
1977 #ifndef OPENSSL_NO_PSK
1978     ret->psk_identity_hint = NULL;
1979     ret->psk_client_callback = NULL;
1980     ret->psk_server_callback = NULL;
1981 #endif
1982 #ifndef OPENSSL_NO_SRP
1983     if(!SSL_CTX_SRP_CTX_init(ret))
1984         goto err;
1985 #endif
1986 #ifndef OPENSSL_NO_ENGINE
1987     ret->client_cert_engine = NULL;
1988 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
1989 #  define eng_strx(x)     #x
1990 #  define eng_str(x)      eng_strx(x)
1991     /* Use specific client engine automatically... ignore errors */
1992     {
1993         ENGINE *eng;
1994         eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1995         if (!eng) {
1996             ERR_clear_error();
1997             ENGINE_load_builtin_engines();
1998             eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1999         }
2000         if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
2001             ERR_clear_error();
2002     }
2003 # endif
2004 #endif
2005     /*
2006      * Default is to connect to non-RI servers. When RI is more widely
2007      * deployed might change this.
2008      */
2009     ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
2010
2011     return (ret);
2012  err:
2013     SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2014  err2:
2015     if (ret != NULL)
2016         SSL_CTX_free(ret);
2017     return (NULL);
2018 }
2019
2020 void SSL_CTX_free(SSL_CTX *a)
2021 {
2022     int i;
2023
2024     if (a == NULL)
2025         return;
2026
2027     i = CRYPTO_add(&a->references, -1, CRYPTO_LOCK_SSL_CTX);
2028 #ifdef REF_PRINT
2029     REF_PRINT("SSL_CTX", a);
2030 #endif
2031     if (i > 0)
2032         return;
2033 #ifdef REF_CHECK
2034     if (i < 0) {
2035         fprintf(stderr, "SSL_CTX_free, bad reference count\n");
2036         abort();                /* ok */
2037     }
2038 #endif
2039
2040     if (a->param)
2041         X509_VERIFY_PARAM_free(a->param);
2042
2043     /*
2044      * Free internal session cache. However: the remove_cb() may reference
2045      * the ex_data of SSL_CTX, thus the ex_data store can only be removed
2046      * after the sessions were flushed.
2047      * As the ex_data handling routines might also touch the session cache,
2048      * the most secure solution seems to be: empty (flush) the cache, then
2049      * free ex_data, then finally free the cache.
2050      * (See ticket [openssl.org #212].)
2051      */
2052     if (a->sessions != NULL)
2053         SSL_CTX_flush_sessions(a, 0);
2054
2055     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
2056
2057     if (a->sessions != NULL)
2058         lh_SSL_SESSION_free(a->sessions);
2059
2060     if (a->cert_store != NULL)
2061         X509_STORE_free(a->cert_store);
2062     if (a->cipher_list != NULL)
2063         sk_SSL_CIPHER_free(a->cipher_list);
2064     if (a->cipher_list_by_id != NULL)
2065         sk_SSL_CIPHER_free(a->cipher_list_by_id);
2066     if (a->cert != NULL)
2067         ssl_cert_free(a->cert);
2068     if (a->client_CA != NULL)
2069         sk_X509_NAME_pop_free(a->client_CA, X509_NAME_free);
2070     if (a->extra_certs != NULL)
2071         sk_X509_pop_free(a->extra_certs, X509_free);
2072     a->comp_methods = NULL;
2073
2074 #ifndef OPENSSL_NO_SRTP
2075     if (a->srtp_profiles)
2076         sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
2077 #endif
2078
2079 #ifndef OPENSSL_NO_PSK
2080     if (a->psk_identity_hint)
2081         OPENSSL_free(a->psk_identity_hint);
2082 #endif
2083 #ifndef OPENSSL_NO_SRP
2084     SSL_CTX_SRP_CTX_free(a);
2085 #endif
2086 #ifndef OPENSSL_NO_ENGINE
2087     if (a->client_cert_engine)
2088         ENGINE_finish(a->client_cert_engine);
2089 #endif
2090
2091 #ifndef OPENSSL_NO_TLSEXT
2092 # ifndef OPENSSL_NO_EC
2093     if (a->tlsext_ecpointformatlist)
2094         OPENSSL_free(a->tlsext_ecpointformatlist);
2095     if (a->tlsext_ellipticcurvelist)
2096         OPENSSL_free(a->tlsext_ellipticcurvelist);
2097 # endif                         /* OPENSSL_NO_EC */
2098     if (a->alpn_client_proto_list != NULL)
2099         OPENSSL_free(a->alpn_client_proto_list);
2100 #endif
2101
2102     OPENSSL_free(a);
2103 }
2104
2105 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2106 {
2107     ctx->default_passwd_callback = cb;
2108 }
2109
2110 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2111 {
2112     ctx->default_passwd_callback_userdata = u;
2113 }
2114
2115 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
2116                                       int (*cb) (X509_STORE_CTX *, void *),
2117                                       void *arg)
2118 {
2119     ctx->app_verify_callback = cb;
2120     ctx->app_verify_arg = arg;
2121 }
2122
2123 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
2124                         int (*cb) (int, X509_STORE_CTX *))
2125 {
2126     ctx->verify_mode = mode;
2127     ctx->default_verify_callback = cb;
2128 }
2129
2130 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
2131 {
2132     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2133 }
2134
2135 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg),
2136                          void *arg)
2137 {
2138     ssl_cert_set_cert_cb(c->cert, cb, arg);
2139 }
2140
2141 void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
2142 {
2143     ssl_cert_set_cert_cb(s->cert, cb, arg);
2144 }
2145
2146 void ssl_set_cert_masks(CERT *c, const SSL_CIPHER *cipher)
2147 {
2148     CERT_PKEY *cpk;
2149     int rsa_enc, rsa_tmp, rsa_sign, dh_tmp, dh_rsa, dh_dsa, dsa_sign;
2150     int rsa_enc_export, dh_rsa_export, dh_dsa_export;
2151     int rsa_tmp_export, dh_tmp_export, kl;
2152     unsigned long mask_k, mask_a, emask_k, emask_a;
2153 #ifndef OPENSSL_NO_EC
2154     int have_ecc_cert, ecdsa_ok, ecc_pkey_size;
2155     int have_ecdh_tmp, ecdh_ok;
2156     X509 *x = NULL;
2157     EVP_PKEY *ecc_pkey = NULL;
2158     int signature_nid = 0, pk_nid = 0, md_nid = 0;
2159 #endif
2160     if (c == NULL)
2161         return;
2162
2163     kl = SSL_C_EXPORT_PKEYLENGTH(cipher);
2164
2165 #ifndef OPENSSL_NO_RSA
2166     rsa_tmp = (c->rsa_tmp != NULL || c->rsa_tmp_cb != NULL);
2167     rsa_tmp_export = (c->rsa_tmp_cb != NULL ||
2168                       (rsa_tmp && RSA_size(c->rsa_tmp) * 8 <= kl));
2169 #else
2170     rsa_tmp = rsa_tmp_export = 0;
2171 #endif
2172 #ifndef OPENSSL_NO_DH
2173     dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL || c->dh_tmp_auto);
2174     dh_tmp_export = !c->dh_tmp_auto && (c->dh_tmp_cb != NULL ||
2175                                         (dh_tmp
2176                                          && DH_size(c->dh_tmp) * 8 <= kl));
2177 #else
2178     dh_tmp = dh_tmp_export = 0;
2179 #endif
2180
2181 #ifndef OPENSSL_NO_EC
2182     have_ecdh_tmp = (c->ecdh_tmp || c->ecdh_tmp_cb || c->ecdh_tmp_auto);
2183 #endif
2184     cpk = &(c->pkeys[SSL_PKEY_RSA_ENC]);
2185     rsa_enc = cpk->valid_flags & CERT_PKEY_VALID;
2186     rsa_enc_export = (rsa_enc && EVP_PKEY_size(cpk->privatekey) * 8 <= kl);
2187     cpk = &(c->pkeys[SSL_PKEY_RSA_SIGN]);
2188     rsa_sign = cpk->valid_flags & CERT_PKEY_SIGN;
2189     cpk = &(c->pkeys[SSL_PKEY_DSA_SIGN]);
2190     dsa_sign = cpk->valid_flags & CERT_PKEY_SIGN;
2191     cpk = &(c->pkeys[SSL_PKEY_DH_RSA]);
2192     dh_rsa = cpk->valid_flags & CERT_PKEY_VALID;
2193     dh_rsa_export = (dh_rsa && EVP_PKEY_size(cpk->privatekey) * 8 <= kl);
2194     cpk = &(c->pkeys[SSL_PKEY_DH_DSA]);
2195 /* FIX THIS EAY EAY EAY */
2196     dh_dsa = cpk->valid_flags & CERT_PKEY_VALID;
2197     dh_dsa_export = (dh_dsa && EVP_PKEY_size(cpk->privatekey) * 8 <= kl);
2198     cpk = &(c->pkeys[SSL_PKEY_ECC]);
2199 #ifndef OPENSSL_NO_EC
2200     have_ecc_cert = cpk->valid_flags & CERT_PKEY_VALID;
2201 #endif
2202     mask_k = 0;
2203     mask_a = 0;
2204     emask_k = 0;
2205     emask_a = 0;
2206
2207 #ifdef CIPHER_DEBUG
2208     fprintf(stderr,
2209             "rt=%d rte=%d dht=%d ecdht=%d re=%d ree=%d rs=%d ds=%d dhr=%d dhd=%d\n",
2210             rsa_tmp, rsa_tmp_export, dh_tmp, have_ecdh_tmp, rsa_enc,
2211             rsa_enc_export, rsa_sign, dsa_sign, dh_rsa, dh_dsa);
2212 #endif
2213
2214     cpk = &(c->pkeys[SSL_PKEY_GOST01]);
2215     if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2216         mask_k |= SSL_kGOST;
2217         mask_a |= SSL_aGOST01;
2218     }
2219     cpk = &(c->pkeys[SSL_PKEY_GOST94]);
2220     if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2221         mask_k |= SSL_kGOST;
2222         mask_a |= SSL_aGOST94;
2223     }
2224
2225     if (rsa_enc || (rsa_tmp && rsa_sign))
2226         mask_k |= SSL_kRSA;
2227     if (rsa_enc_export || (rsa_tmp_export && (rsa_sign || rsa_enc)))
2228         emask_k |= SSL_kRSA;
2229
2230     if (dh_tmp_export)
2231         emask_k |= SSL_kDHE;
2232
2233     if (dh_tmp)
2234         mask_k |= SSL_kDHE;
2235
2236     if (dh_rsa)
2237         mask_k |= SSL_kDHr;
2238     if (dh_rsa_export)
2239         emask_k |= SSL_kDHr;
2240
2241     if (dh_dsa)
2242         mask_k |= SSL_kDHd;
2243     if (dh_dsa_export)
2244         emask_k |= SSL_kDHd;
2245
2246     if (emask_k & (SSL_kDHr | SSL_kDHd))
2247         mask_a |= SSL_aDH;
2248
2249     if (rsa_enc || rsa_sign) {
2250         mask_a |= SSL_aRSA;
2251         emask_a |= SSL_aRSA;
2252     }
2253
2254     if (dsa_sign) {
2255         mask_a |= SSL_aDSS;
2256         emask_a |= SSL_aDSS;
2257     }
2258
2259     mask_a |= SSL_aNULL;
2260     emask_a |= SSL_aNULL;
2261
2262 #ifndef OPENSSL_NO_KRB5
2263     mask_k |= SSL_kKRB5;
2264     mask_a |= SSL_aKRB5;
2265     emask_k |= SSL_kKRB5;
2266     emask_a |= SSL_aKRB5;
2267 #endif
2268
2269     /*
2270      * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
2271      * depending on the key usage extension.
2272      */
2273 #ifndef OPENSSL_NO_EC
2274     if (have_ecc_cert) {
2275         cpk = &c->pkeys[SSL_PKEY_ECC];
2276         x = cpk->x509;
2277         /* This call populates extension flags (ex_flags) */
2278         X509_check_purpose(x, -1, 0);
2279         ecdh_ok = (x->ex_flags & EXFLAG_KUSAGE) ?
2280             (x->ex_kusage & X509v3_KU_KEY_AGREEMENT) : 1;
2281         ecdsa_ok = (x->ex_flags & EXFLAG_KUSAGE) ?
2282             (x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE) : 1;
2283         if (!(cpk->valid_flags & CERT_PKEY_SIGN))
2284             ecdsa_ok = 0;
2285         ecc_pkey = X509_get_pubkey(x);
2286         ecc_pkey_size = (ecc_pkey != NULL) ? EVP_PKEY_bits(ecc_pkey) : 0;
2287         EVP_PKEY_free(ecc_pkey);
2288         if ((x->sig_alg) && (x->sig_alg->algorithm)) {
2289             signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
2290             OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid);
2291         }
2292         if (ecdh_ok) {
2293
2294             if (pk_nid == NID_rsaEncryption || pk_nid == NID_rsa) {
2295                 mask_k |= SSL_kECDHr;
2296                 mask_a |= SSL_aECDH;
2297                 if (ecc_pkey_size <= 163) {
2298                     emask_k |= SSL_kECDHr;
2299                     emask_a |= SSL_aECDH;
2300                 }
2301             }
2302
2303             if (pk_nid == NID_X9_62_id_ecPublicKey) {
2304                 mask_k |= SSL_kECDHe;
2305                 mask_a |= SSL_aECDH;
2306                 if (ecc_pkey_size <= 163) {
2307                     emask_k |= SSL_kECDHe;
2308                     emask_a |= SSL_aECDH;
2309                 }
2310             }
2311         }
2312         if (ecdsa_ok) {
2313             mask_a |= SSL_aECDSA;
2314             emask_a |= SSL_aECDSA;
2315         }
2316     }
2317 #endif
2318
2319 #ifndef OPENSSL_NO_EC
2320     if (have_ecdh_tmp) {
2321         mask_k |= SSL_kECDHE;
2322         emask_k |= SSL_kECDHE;
2323     }
2324 #endif
2325
2326 #ifndef OPENSSL_NO_PSK
2327     mask_k |= SSL_kPSK;
2328     mask_a |= SSL_aPSK;
2329     emask_k |= SSL_kPSK;
2330     emask_a |= SSL_aPSK;
2331 #endif
2332
2333     c->mask_k = mask_k;
2334     c->mask_a = mask_a;
2335     c->export_mask_k = emask_k;
2336     c->export_mask_a = emask_a;
2337     c->valid = 1;
2338 }
2339
2340 /* This handy macro borrowed from crypto/x509v3/v3_purp.c */
2341 #define ku_reject(x, usage) \
2342         (((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
2343
2344 #ifndef OPENSSL_NO_EC
2345
2346 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
2347 {
2348     unsigned long alg_k, alg_a;
2349     EVP_PKEY *pkey = NULL;
2350     int keysize = 0;
2351     int signature_nid = 0, md_nid = 0, pk_nid = 0;
2352     const SSL_CIPHER *cs = s->s3->tmp.new_cipher;
2353
2354     alg_k = cs->algorithm_mkey;
2355     alg_a = cs->algorithm_auth;
2356
2357     if (SSL_C_IS_EXPORT(cs)) {
2358         /* ECDH key length in export ciphers must be <= 163 bits */
2359         pkey = X509_get_pubkey(x);
2360         if (pkey == NULL)
2361             return 0;
2362         keysize = EVP_PKEY_bits(pkey);
2363         EVP_PKEY_free(pkey);
2364         if (keysize > 163)
2365             return 0;
2366     }
2367
2368     /* This call populates the ex_flags field correctly */
2369     X509_check_purpose(x, -1, 0);
2370     if ((x->sig_alg) && (x->sig_alg->algorithm)) {
2371         signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
2372         OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid);
2373     }
2374     if (alg_k & SSL_kECDHe || alg_k & SSL_kECDHr) {
2375         /* key usage, if present, must allow key agreement */
2376         if (ku_reject(x, X509v3_KU_KEY_AGREEMENT)) {
2377             SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2378                    SSL_R_ECC_CERT_NOT_FOR_KEY_AGREEMENT);
2379             return 0;
2380         }
2381         if ((alg_k & SSL_kECDHe) && TLS1_get_version(s) < TLS1_2_VERSION) {
2382             /* signature alg must be ECDSA */
2383             if (pk_nid != NID_X9_62_id_ecPublicKey) {
2384                 SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2385                        SSL_R_ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE);
2386                 return 0;
2387             }
2388         }
2389         if ((alg_k & SSL_kECDHr) && TLS1_get_version(s) < TLS1_2_VERSION) {
2390             /* signature alg must be RSA */
2391
2392             if (pk_nid != NID_rsaEncryption && pk_nid != NID_rsa) {
2393                 SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2394                        SSL_R_ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE);
2395                 return 0;
2396             }
2397         }
2398     }
2399     if (alg_a & SSL_aECDSA) {
2400         /* key usage, if present, must allow signing */
2401         if (ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE)) {
2402             SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2403                    SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2404             return 0;
2405         }
2406     }
2407
2408     return 1;                   /* all checks are ok */
2409 }
2410
2411 #endif
2412
2413 static int ssl_get_server_cert_index(const SSL *s)
2414 {
2415     int idx;
2416     idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
2417     if (idx == SSL_PKEY_RSA_ENC && !s->cert->pkeys[SSL_PKEY_RSA_ENC].x509)
2418         idx = SSL_PKEY_RSA_SIGN;
2419     if (idx == -1)
2420         SSLerr(SSL_F_SSL_GET_SERVER_CERT_INDEX, ERR_R_INTERNAL_ERROR);
2421     return idx;
2422 }
2423
2424 CERT_PKEY *ssl_get_server_send_pkey(const SSL *s)
2425 {
2426     CERT *c;
2427     int i;
2428
2429     c = s->cert;
2430     if (!s->s3 || !s->s3->tmp.new_cipher)
2431         return NULL;
2432     ssl_set_cert_masks(c, s->s3->tmp.new_cipher);
2433
2434 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
2435     /*
2436      * Broken protocol test: return last used certificate: which may mismatch
2437      * the one expected.
2438      */
2439     if (c->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
2440         return c->key;
2441 #endif
2442
2443     i = ssl_get_server_cert_index(s);
2444
2445     /* This may or may not be an error. */
2446     if (i < 0)
2447         return NULL;
2448
2449     /* May be NULL. */
2450     return &c->pkeys[i];
2451 }
2452
2453 EVP_PKEY *ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher,
2454                             const EVP_MD **pmd)
2455 {
2456     unsigned long alg_a;
2457     CERT *c;
2458     int idx = -1;
2459
2460     alg_a = cipher->algorithm_auth;
2461     c = s->cert;
2462
2463 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
2464     /*
2465      * Broken protocol test: use last key: which may mismatch the one
2466      * expected.
2467      */
2468     if (c->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
2469         idx = c->key - c->pkeys;
2470     else
2471 #endif
2472
2473     if ((alg_a & SSL_aDSS) &&
2474             (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
2475         idx = SSL_PKEY_DSA_SIGN;
2476     else if (alg_a & SSL_aRSA) {
2477         if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
2478             idx = SSL_PKEY_RSA_SIGN;
2479         else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
2480             idx = SSL_PKEY_RSA_ENC;
2481     } else if ((alg_a & SSL_aECDSA) &&
2482                (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2483         idx = SSL_PKEY_ECC;
2484     if (idx == -1) {
2485         SSLerr(SSL_F_SSL_GET_SIGN_PKEY, ERR_R_INTERNAL_ERROR);
2486         return (NULL);
2487     }
2488     if (pmd)
2489         *pmd = c->pkeys[idx].digest;
2490     return c->pkeys[idx].privatekey;
2491 }
2492
2493 #ifndef OPENSSL_NO_TLSEXT
2494 int ssl_get_server_cert_serverinfo(SSL *s, const unsigned char **serverinfo,
2495                                    size_t *serverinfo_length)
2496 {
2497     CERT *c = NULL;
2498     int i = 0;
2499     *serverinfo_length = 0;
2500
2501     c = s->cert;
2502     i = ssl_get_server_cert_index(s);
2503
2504     if (i == -1)
2505         return 0;
2506     if (c->pkeys[i].serverinfo == NULL)
2507         return 0;
2508
2509     *serverinfo = c->pkeys[i].serverinfo;
2510     *serverinfo_length = c->pkeys[i].serverinfo_length;
2511     return 1;
2512 }
2513 #endif
2514
2515 void ssl_update_cache(SSL *s, int mode)
2516 {
2517     int i;
2518
2519     /*
2520      * If the session_id_length is 0, we are not supposed to cache it, and it
2521      * would be rather hard to do anyway :-)
2522      */
2523     if (s->session->session_id_length == 0)
2524         return;
2525
2526     i = s->session_ctx->session_cache_mode;
2527     if ((i & mode) && (!s->hit)
2528         && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
2529             || SSL_CTX_add_session(s->session_ctx, s->session))
2530         && (s->session_ctx->new_session_cb != NULL)) {
2531         CRYPTO_add(&s->session->references, 1, CRYPTO_LOCK_SSL_SESSION);
2532         if (!s->session_ctx->new_session_cb(s, s->session))
2533             SSL_SESSION_free(s->session);
2534     }
2535
2536     /* auto flush every 255 connections */
2537     if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
2538         if ((((mode & SSL_SESS_CACHE_CLIENT)
2539               ? s->session_ctx->stats.sess_connect_good
2540               : s->session_ctx->stats.sess_accept_good) & 0xff) == 0xff) {
2541             SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
2542         }
2543     }
2544 }
2545
2546 const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx)
2547 {
2548     return ctx->method;
2549 }
2550
2551 const SSL_METHOD *SSL_get_ssl_method(SSL *s)
2552 {
2553     return (s->method);
2554 }
2555
2556 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
2557 {
2558     int conn = -1;
2559     int ret = 1;
2560
2561     if (s->method != meth) {
2562         if (s->handshake_func != NULL)
2563             conn = (s->handshake_func == s->method->ssl_connect);
2564
2565         if (s->method->version == meth->version)
2566             s->method = meth;
2567         else {
2568             s->method->ssl_free(s);
2569             s->method = meth;
2570             ret = s->method->ssl_new(s);
2571         }
2572
2573         if (conn == 1)
2574             s->handshake_func = meth->ssl_connect;
2575         else if (conn == 0)
2576             s->handshake_func = meth->ssl_accept;
2577     }
2578     return (ret);
2579 }
2580
2581 int SSL_get_error(const SSL *s, int i)
2582 {
2583     int reason;
2584     unsigned long l;
2585     BIO *bio;
2586
2587     if (i > 0)
2588         return (SSL_ERROR_NONE);
2589
2590     /*
2591      * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
2592      * where we do encode the error
2593      */
2594     if ((l = ERR_peek_error()) != 0) {
2595         if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2596             return (SSL_ERROR_SYSCALL);
2597         else
2598             return (SSL_ERROR_SSL);
2599     }
2600
2601     if ((i < 0) && SSL_want_read(s)) {
2602         bio = SSL_get_rbio(s);
2603         if (BIO_should_read(bio))
2604             return (SSL_ERROR_WANT_READ);
2605         else if (BIO_should_write(bio))
2606             /*
2607              * This one doesn't make too much sense ... We never try to write
2608              * to the rbio, and an application program where rbio and wbio
2609              * are separate couldn't even know what it should wait for.
2610              * However if we ever set s->rwstate incorrectly (so that we have
2611              * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
2612              * wbio *are* the same, this test works around that bug; so it
2613              * might be safer to keep it.
2614              */
2615             return (SSL_ERROR_WANT_WRITE);
2616         else if (BIO_should_io_special(bio)) {
2617             reason = BIO_get_retry_reason(bio);
2618             if (reason == BIO_RR_CONNECT)
2619                 return (SSL_ERROR_WANT_CONNECT);
2620             else if (reason == BIO_RR_ACCEPT)
2621                 return (SSL_ERROR_WANT_ACCEPT);
2622             else
2623                 return (SSL_ERROR_SYSCALL); /* unknown */
2624         }
2625     }
2626
2627     if ((i < 0) && SSL_want_write(s)) {
2628         bio = SSL_get_wbio(s);
2629         if (BIO_should_write(bio))
2630             return (SSL_ERROR_WANT_WRITE);
2631         else if (BIO_should_read(bio))
2632             /*
2633              * See above (SSL_want_read(s) with BIO_should_write(bio))
2634              */
2635             return (SSL_ERROR_WANT_READ);
2636         else if (BIO_should_io_special(bio)) {
2637             reason = BIO_get_retry_reason(bio);
2638             if (reason == BIO_RR_CONNECT)
2639                 return (SSL_ERROR_WANT_CONNECT);
2640             else if (reason == BIO_RR_ACCEPT)
2641                 return (SSL_ERROR_WANT_ACCEPT);
2642             else
2643                 return (SSL_ERROR_SYSCALL);
2644         }
2645     }
2646     if ((i < 0) && SSL_want_x509_lookup(s)) {
2647         return (SSL_ERROR_WANT_X509_LOOKUP);
2648     }
2649
2650     if (i == 0) {
2651         if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2652             (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
2653             return (SSL_ERROR_ZERO_RETURN);
2654     }
2655     return (SSL_ERROR_SYSCALL);
2656 }
2657
2658 int SSL_do_handshake(SSL *s)
2659 {
2660     int ret = 1;
2661
2662     if (s->handshake_func == NULL) {
2663         SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
2664         return (-1);
2665     }
2666
2667     s->method->ssl_renegotiate_check(s);
2668
2669     if (SSL_in_init(s) || SSL_in_before(s)) {
2670         ret = s->handshake_func(s);
2671     }
2672     return (ret);
2673 }
2674
2675 /*
2676  * For the next 2 functions, SSL_clear() sets shutdown and so one of these
2677  * calls will reset it
2678  */
2679 void SSL_set_accept_state(SSL *s)
2680 {
2681     s->server = 1;
2682     s->shutdown = 0;
2683     s->state = SSL_ST_ACCEPT | SSL_ST_BEFORE;
2684     s->handshake_func = s->method->ssl_accept;
2685     /* clear the current cipher */
2686     ssl_clear_cipher_ctx(s);
2687     ssl_clear_hash_ctx(&s->read_hash);
2688     ssl_clear_hash_ctx(&s->write_hash);
2689 }
2690
2691 void SSL_set_connect_state(SSL *s)
2692 {
2693     s->server = 0;
2694     s->shutdown = 0;
2695     s->state = SSL_ST_CONNECT | SSL_ST_BEFORE;
2696     s->handshake_func = s->method->ssl_connect;
2697     /* clear the current cipher */
2698     ssl_clear_cipher_ctx(s);
2699     ssl_clear_hash_ctx(&s->read_hash);
2700     ssl_clear_hash_ctx(&s->write_hash);
2701 }
2702
2703 int ssl_undefined_function(SSL *s)
2704 {
2705     SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2706     return (0);
2707 }
2708
2709 int ssl_undefined_void_function(void)
2710 {
2711     SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
2712            ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2713     return (0);
2714 }
2715
2716 int ssl_undefined_const_function(const SSL *s)
2717 {
2718     SSLerr(SSL_F_SSL_UNDEFINED_CONST_FUNCTION,
2719            ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2720     return (0);
2721 }
2722
2723 SSL_METHOD *ssl_bad_method(int ver)
2724 {
2725     SSLerr(SSL_F_SSL_BAD_METHOD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2726     return (NULL);
2727 }
2728
2729 const char *SSL_get_version(const SSL *s)
2730 {
2731     if (s->version == TLS1_2_VERSION)
2732         return ("TLSv1.2");
2733     else if (s->version == TLS1_1_VERSION)
2734         return ("TLSv1.1");
2735     else if (s->version == TLS1_VERSION)
2736         return ("TLSv1");
2737     else if (s->version == SSL3_VERSION)
2738         return ("SSLv3");
2739     else if (s->version == DTLS1_BAD_VER)
2740         return ("DTLSv0.9");
2741     else if (s->version == DTLS1_VERSION)
2742         return ("DTLSv1");
2743     else if (s->version == DTLS1_2_VERSION)
2744         return ("DTLSv1.2");
2745     else
2746         return ("unknown");
2747 }
2748
2749 SSL *SSL_dup(SSL *s)
2750 {
2751     STACK_OF(X509_NAME) *sk;
2752     X509_NAME *xn;
2753     SSL *ret;
2754     int i;
2755
2756     if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
2757         return (NULL);
2758
2759     ret->version = s->version;
2760     ret->type = s->type;
2761     ret->method = s->method;
2762
2763     if (s->session != NULL) {
2764         /* This copies session-id, SSL_METHOD, sid_ctx, and 'cert' */
2765         if(!SSL_copy_session_id(ret, s))
2766             goto err;
2767     } else {
2768         /*
2769          * No session has been established yet, so we have to expect that
2770          * s->cert or ret->cert will be changed later -- they should not both
2771          * point to the same object, and thus we can't use
2772          * SSL_copy_session_id.
2773          */
2774
2775         ret->method->ssl_free(ret);
2776         ret->method = s->method;
2777         ret->method->ssl_new(ret);
2778
2779         if (s->cert != NULL) {
2780             if (ret->cert != NULL) {
2781                 ssl_cert_free(ret->cert);
2782             }
2783             ret->cert = ssl_cert_dup(s->cert);
2784             if (ret->cert == NULL)
2785                 goto err;
2786         }
2787
2788         if(!SSL_set_session_id_context(ret, s->sid_ctx, s->sid_ctx_length))
2789             goto err;
2790     }
2791
2792     ret->options = s->options;
2793     ret->mode = s->mode;
2794     SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
2795     SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
2796     ret->msg_callback = s->msg_callback;
2797     ret->msg_callback_arg = s->msg_callback_arg;
2798     SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
2799     SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
2800     ret->generate_session_id = s->generate_session_id;
2801
2802     SSL_set_info_callback(ret, SSL_get_info_callback(s));
2803
2804     ret->debug = s->debug;
2805
2806     /* copy app data, a little dangerous perhaps */
2807     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
2808         goto err;
2809
2810     /* setup rbio, and wbio */
2811     if (s->rbio != NULL) {
2812         if (!BIO_dup_state(s->rbio, (char *)&ret->rbio))
2813             goto err;
2814     }
2815     if (s->wbio != NULL) {
2816         if (s->wbio != s->rbio) {
2817             if (!BIO_dup_state(s->wbio, (char *)&ret->wbio))
2818                 goto err;
2819         } else
2820             ret->wbio = ret->rbio;
2821     }
2822     ret->rwstate = s->rwstate;
2823     ret->in_handshake = s->in_handshake;
2824     ret->handshake_func = s->handshake_func;
2825     ret->server = s->server;
2826     ret->renegotiate = s->renegotiate;
2827     ret->new_session = s->new_session;
2828     ret->quiet_shutdown = s->quiet_shutdown;
2829     ret->shutdown = s->shutdown;
2830     ret->state = s->state;      /* SSL_dup does not really work at any state,
2831                                  * though */
2832     RECORD_LAYER_dup(&ret->rlayer, &s->rlayer);
2833     ret->init_num = 0;          /* would have to copy ret->init_buf,
2834                                  * ret->init_msg, ret->init_num,
2835                                  * ret->init_off */
2836     ret->hit = s->hit;
2837
2838     X509_VERIFY_PARAM_inherit(ret->param, s->param);
2839
2840     /* dup the cipher_list and cipher_list_by_id stacks */
2841     if (s->cipher_list != NULL) {
2842         if ((ret->cipher_list = sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
2843             goto err;
2844     }
2845     if (s->cipher_list_by_id != NULL)
2846         if ((ret->cipher_list_by_id = sk_SSL_CIPHER_dup(s->cipher_list_by_id))
2847             == NULL)
2848             goto err;
2849
2850     /* Dup the client_CA list */
2851     if (s->client_CA != NULL) {
2852         if ((sk = sk_X509_NAME_dup(s->client_CA)) == NULL)
2853             goto err;
2854         ret->client_CA = sk;
2855         for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2856             xn = sk_X509_NAME_value(sk, i);
2857             if (sk_X509_NAME_set(sk, i, X509_NAME_dup(xn)) == NULL) {
2858                 X509_NAME_free(xn);
2859                 goto err;
2860             }
2861         }
2862     }
2863
2864     if (0) {
2865  err:
2866         if (ret != NULL)
2867             SSL_free(ret);
2868         ret = NULL;
2869     }
2870     return (ret);
2871 }
2872
2873 void ssl_clear_cipher_ctx(SSL *s)
2874 {
2875     if (s->enc_read_ctx != NULL) {
2876         EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
2877         OPENSSL_free(s->enc_read_ctx);
2878         s->enc_read_ctx = NULL;
2879     }
2880     if (s->enc_write_ctx != NULL) {
2881         EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
2882         OPENSSL_free(s->enc_write_ctx);
2883         s->enc_write_ctx = NULL;
2884     }
2885 #ifndef OPENSSL_NO_COMP
2886     if (s->expand != NULL) {
2887         COMP_CTX_free(s->expand);
2888         s->expand = NULL;
2889     }
2890     if (s->compress != NULL) {
2891         COMP_CTX_free(s->compress);
2892         s->compress = NULL;
2893     }
2894 #endif
2895 }
2896
2897 X509 *SSL_get_certificate(const SSL *s)
2898 {
2899     if (s->cert != NULL)
2900         return (s->cert->key->x509);
2901     else
2902         return (NULL);
2903 }
2904
2905 EVP_PKEY *SSL_get_privatekey(const SSL *s)
2906 {
2907     if (s->cert != NULL)
2908         return (s->cert->key->privatekey);
2909     else
2910         return (NULL);
2911 }
2912
2913 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
2914 {
2915     if (ctx->cert != NULL)
2916         return ctx->cert->key->x509;
2917     else
2918         return NULL;
2919 }
2920
2921 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
2922 {
2923     if (ctx->cert != NULL)
2924         return ctx->cert->key->privatekey;
2925     else
2926         return NULL;
2927 }
2928
2929 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
2930 {
2931     if ((s->session != NULL) && (s->session->cipher != NULL))
2932         return (s->session->cipher);
2933     return (NULL);
2934 }
2935
2936 #ifdef OPENSSL_NO_COMP
2937 const void *SSL_get_current_compression(SSL *s)
2938 {
2939     return NULL;
2940 }
2941
2942 const void *SSL_get_current_expansion(SSL *s)
2943 {
2944     return NULL;
2945 }
2946 #else
2947
2948 const COMP_METHOD *SSL_get_current_compression(SSL *s)
2949 {
2950     if (s->compress != NULL)
2951         return (s->compress->meth);
2952     return (NULL);
2953 }
2954
2955 const COMP_METHOD *SSL_get_current_expansion(SSL *s)
2956 {
2957     if (s->expand != NULL)
2958         return (s->expand->meth);
2959     return (NULL);
2960 }
2961 #endif
2962
2963 int ssl_init_wbio_buffer(SSL *s, int push)
2964 {
2965     BIO *bbio;
2966
2967     if (s->bbio == NULL) {
2968         bbio = BIO_new(BIO_f_buffer());
2969         if (bbio == NULL)
2970             return (0);
2971         s->bbio = bbio;
2972     } else {
2973         bbio = s->bbio;
2974         if (s->bbio == s->wbio)
2975             s->wbio = BIO_pop(s->wbio);
2976     }
2977     (void)BIO_reset(bbio);
2978 /*      if (!BIO_set_write_buffer_size(bbio,16*1024)) */
2979     if (!BIO_set_read_buffer_size(bbio, 1)) {
2980         SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
2981         return (0);
2982     }
2983     if (push) {
2984         if (s->wbio != bbio)
2985             s->wbio = BIO_push(bbio, s->wbio);
2986     } else {
2987         if (s->wbio == bbio)
2988             s->wbio = BIO_pop(bbio);
2989     }
2990     return (1);
2991 }
2992
2993 void ssl_free_wbio_buffer(SSL *s)
2994 {
2995     if (s->bbio == NULL)
2996         return;
2997
2998     if (s->bbio == s->wbio) {
2999         /* remove buffering */
3000         s->wbio = BIO_pop(s->wbio);
3001 #ifdef REF_CHECK                /* not the usual REF_CHECK, but this avoids
3002                                  * adding one more preprocessor symbol */
3003         assert(s->wbio != NULL);
3004 #endif
3005     }
3006     BIO_free(s->bbio);
3007     s->bbio = NULL;
3008 }
3009
3010 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
3011 {
3012     ctx->quiet_shutdown = mode;
3013 }
3014
3015 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
3016 {
3017     return (ctx->quiet_shutdown);
3018 }
3019
3020 void SSL_set_quiet_shutdown(SSL *s, int mode)
3021 {
3022     s->quiet_shutdown = mode;
3023 }
3024
3025 int SSL_get_quiet_shutdown(const SSL *s)
3026 {
3027     return (s->quiet_shutdown);
3028 }
3029
3030 void SSL_set_shutdown(SSL *s, int mode)
3031 {
3032     s->shutdown = mode;
3033 }
3034
3035 int SSL_get_shutdown(const SSL *s)
3036 {
3037     return (s->shutdown);
3038 }
3039
3040 int SSL_version(const SSL *s)
3041 {
3042     return (s->version);
3043 }
3044
3045 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
3046 {
3047     return (ssl->ctx);
3048 }
3049
3050 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
3051 {
3052     CERT *new_cert;
3053     if (ssl->ctx == ctx)
3054         return ssl->ctx;
3055 #ifndef OPENSSL_NO_TLSEXT
3056     if (ctx == NULL)
3057         ctx = ssl->initial_ctx;
3058 #endif
3059     new_cert = ssl_cert_dup(ctx->cert);
3060     if (new_cert == NULL) {
3061         return NULL;
3062     }
3063     /* Preserve any already negotiated parameters */
3064     if (ssl->server) {
3065         new_cert->peer_sigalgs = ssl->cert->peer_sigalgs;
3066         new_cert->peer_sigalgslen = ssl->cert->peer_sigalgslen;
3067         ssl->cert->peer_sigalgs = NULL;
3068         new_cert->ciphers_raw = ssl->cert->ciphers_raw;
3069         new_cert->ciphers_rawlen = ssl->cert->ciphers_rawlen;
3070         ssl->cert->ciphers_raw = NULL;
3071     }
3072     ssl_cert_free(ssl->cert);
3073     ssl->cert = new_cert;
3074
3075     /*
3076      * Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
3077      * so setter APIs must prevent invalid lengths from entering the system.
3078      */
3079     OPENSSL_assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx));
3080
3081     /*
3082      * If the session ID context matches that of the parent SSL_CTX,
3083      * inherit it from the new SSL_CTX as well. If however the context does
3084      * not match (i.e., it was set per-ssl with SSL_set_session_id_context),
3085      * leave it unchanged.
3086      */
3087     if ((ssl->ctx != NULL) &&
3088         (ssl->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
3089         (memcmp(ssl->sid_ctx, ssl->ctx->sid_ctx, ssl->sid_ctx_length) == 0)) {
3090         ssl->sid_ctx_length = ctx->sid_ctx_length;
3091         memcpy(&ssl->sid_ctx, &ctx->sid_ctx, sizeof(ssl->sid_ctx));
3092     }
3093
3094     CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
3095     if (ssl->ctx != NULL)
3096         SSL_CTX_free(ssl->ctx); /* decrement reference count */
3097     ssl->ctx = ctx;
3098
3099     return (ssl->ctx);
3100 }
3101
3102 #ifndef OPENSSL_NO_STDIO
3103 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
3104 {
3105     return (X509_STORE_set_default_paths(ctx->cert_store));
3106 }
3107
3108 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
3109                                   const char *CApath)
3110 {
3111     return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
3112 }
3113 #endif
3114
3115 void SSL_set_info_callback(SSL *ssl,
3116                            void (*cb) (const SSL *ssl, int type, int val))
3117 {
3118     ssl->info_callback = cb;
3119 }
3120
3121 /*
3122  * One compiler (Diab DCC) doesn't like argument names in returned function
3123  * pointer.
3124  */
3125 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
3126                                                int /* type */ ,
3127                                                int /* val */ ) {
3128     return ssl->info_callback;
3129 }
3130
3131 int SSL_state(const SSL *ssl)
3132 {
3133     return (ssl->state);
3134 }
3135
3136 void SSL_set_state(SSL *ssl, int state)
3137 {
3138     ssl->state = state;
3139 }
3140
3141 void SSL_set_verify_result(SSL *ssl, long arg)
3142 {
3143     ssl->verify_result = arg;
3144 }
3145
3146 long SSL_get_verify_result(const SSL *ssl)
3147 {
3148     return (ssl->verify_result);
3149 }
3150
3151 int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
3152                          CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
3153 {
3154     return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp,
3155                                    new_func, dup_func, free_func);
3156 }
3157
3158 int SSL_set_ex_data(SSL *s, int idx, void *arg)
3159 {
3160     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3161 }
3162
3163 void *SSL_get_ex_data(const SSL *s, int idx)
3164 {
3165     return (CRYPTO_get_ex_data(&s->ex_data, idx));
3166 }
3167
3168 int SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
3169                              CRYPTO_EX_dup *dup_func,
3170                              CRYPTO_EX_free *free_func)
3171 {
3172     return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp,
3173                                    new_func, dup_func, free_func);
3174 }
3175
3176 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
3177 {
3178     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3179 }
3180
3181 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
3182 {
3183     return (CRYPTO_get_ex_data(&s->ex_data, idx));
3184 }
3185
3186 int ssl_ok(SSL *s)
3187 {
3188     return (1);
3189 }
3190
3191 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
3192 {
3193     return (ctx->cert_store);
3194 }
3195
3196 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
3197 {
3198     if (ctx->cert_store != NULL)
3199         X509_STORE_free(ctx->cert_store);
3200     ctx->cert_store = store;
3201 }
3202
3203 int SSL_want(const SSL *s)
3204 {
3205     return (s->rwstate);
3206 }
3207
3208 /**
3209  * \brief Set the callback for generating temporary RSA keys.
3210  * \param ctx the SSL context.
3211  * \param cb the callback
3212  */
3213
3214 #ifndef OPENSSL_NO_RSA
3215 void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*cb) (SSL *ssl,
3216                                                             int is_export,
3217                                                             int keylength))
3218 {
3219     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_RSA_CB, (void (*)(void))cb);
3220 }
3221
3222 void SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb) (SSL *ssl,
3223                                                     int is_export,
3224                                                     int keylength))
3225 {
3226     SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_RSA_CB, (void (*)(void))cb);
3227 }
3228 #endif
3229
3230 #ifdef DOXYGEN
3231 /**
3232  * \brief The RSA temporary key callback function.
3233  * \param ssl the SSL session.
3234  * \param is_export \c TRUE if the temp RSA key is for an export ciphersuite.
3235  * \param keylength if \c is_export is \c TRUE, then \c keylength is the size
3236  * of the required key in bits.
3237  * \return the temporary RSA key.
3238  * \sa SSL_CTX_set_tmp_rsa_callback, SSL_set_tmp_rsa_callback
3239  */
3240
3241 RSA *cb(SSL *ssl, int is_export, int keylength)
3242 {
3243 }
3244 #endif
3245
3246 /**
3247  * \brief Set the callback for generating temporary DH keys.
3248  * \param ctx the SSL context.
3249  * \param dh the callback
3250  */
3251
3252 #ifndef OPENSSL_NO_DH
3253 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
3254                                  DH *(*dh) (SSL *ssl, int is_export,
3255                                             int keylength))
3256 {
3257     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3258 }
3259
3260 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
3261                                                   int keylength))
3262 {
3263     SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3264 }
3265 #endif
3266
3267 #ifndef OPENSSL_NO_EC
3268 void SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx,
3269                                    EC_KEY *(*ecdh) (SSL *ssl, int is_export,
3270                                                     int keylength))
3271 {
3272     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH_CB,
3273                           (void (*)(void))ecdh);
3274 }
3275
3276 void SSL_set_tmp_ecdh_callback(SSL *ssl,
3277                                EC_KEY *(*ecdh) (SSL *ssl, int is_export,
3278                                                 int keylength))
3279 {
3280     SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH_CB, (void (*)(void))ecdh);
3281 }
3282 #endif
3283
3284 #ifndef OPENSSL_NO_PSK
3285 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
3286 {
3287     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3288         SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT,
3289                SSL_R_DATA_LENGTH_TOO_LONG);
3290         return 0;
3291     }
3292     if (ctx->psk_identity_hint != NULL)
3293         OPENSSL_free(ctx->psk_identity_hint);
3294     if (identity_hint != NULL) {
3295         ctx->psk_identity_hint = BUF_strdup(identity_hint);
3296         if (ctx->psk_identity_hint == NULL)
3297             return 0;
3298     } else
3299         ctx->psk_identity_hint = NULL;
3300     return 1;
3301 }
3302
3303 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
3304 {
3305     if (s == NULL)
3306         return 0;
3307
3308     if (s->session == NULL)
3309         return 1;               /* session not created yet, ignored */
3310
3311     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3312         SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
3313         return 0;
3314     }
3315     if (s->session->psk_identity_hint != NULL)
3316         OPENSSL_free(s->session->psk_identity_hint);
3317     if (identity_hint != NULL) {
3318         s->session->psk_identity_hint = BUF_strdup(identity_hint);
3319         if (s->session->psk_identity_hint == NULL)
3320             return 0;
3321     } else
3322         s->session->psk_identity_hint = NULL;
3323     return 1;
3324 }
3325
3326 const char *SSL_get_psk_identity_hint(const SSL *s)
3327 {
3328     if (s == NULL || s->session == NULL)
3329         return NULL;
3330     return (s->session->psk_identity_hint);
3331 }
3332
3333 const char *SSL_get_psk_identity(const SSL *s)
3334 {
3335     if (s == NULL || s->session == NULL)
3336         return NULL;
3337     return (s->session->psk_identity);
3338 }
3339
3340 void SSL_set_psk_client_callback(SSL *s,
3341                                  unsigned int (*cb) (SSL *ssl,
3342                                                      const char *hint,
3343                                                      char *identity,
3344                                                      unsigned int
3345                                                      max_identity_len,
3346                                                      unsigned char *psk,
3347                                                      unsigned int
3348                                                      max_psk_len))
3349 {
3350     s->psk_client_callback = cb;
3351 }
3352
3353 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx,
3354                                      unsigned int (*cb) (SSL *ssl,
3355                                                          const char *hint,
3356                                                          char *identity,
3357                                                          unsigned int
3358                                                          max_identity_len,
3359                                                          unsigned char *psk,
3360                                                          unsigned int
3361                                                          max_psk_len))
3362 {
3363     ctx->psk_client_callback = cb;
3364 }
3365
3366 void SSL_set_psk_server_callback(SSL *s,
3367                                  unsigned int (*cb) (SSL *ssl,
3368                                                      const char *identity,
3369                                                      unsigned char *psk,
3370                                                      unsigned int
3371                                                      max_psk_len))
3372 {
3373     s->psk_server_callback = cb;
3374 }
3375
3376 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,
3377                                      unsigned int (*cb) (SSL *ssl,
3378                                                          const char *identity,
3379                                                          unsigned char *psk,
3380                                                          unsigned int
3381                                                          max_psk_len))
3382 {
3383     ctx->psk_server_callback = cb;
3384 }
3385 #endif
3386
3387 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
3388                               void (*cb) (int write_p, int version,
3389                                           int content_type, const void *buf,
3390                                           size_t len, SSL *ssl, void *arg))
3391 {
3392     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3393 }
3394
3395 void SSL_set_msg_callback(SSL *ssl,
3396                           void (*cb) (int write_p, int version,
3397                                       int content_type, const void *buf,
3398                                       size_t len, SSL *ssl, void *arg))
3399 {
3400     SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3401 }
3402
3403 void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
3404                                                 int (*cb) (SSL *ssl,
3405                                                            int
3406                                                            is_forward_secure))
3407 {
3408     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3409                           (void (*)(void))cb);
3410 }
3411
3412 void SSL_set_not_resumable_session_callback(SSL *ssl,
3413                                             int (*cb) (SSL *ssl,
3414                                                        int is_forward_secure))
3415 {
3416     SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3417                       (void (*)(void))cb);
3418 }
3419
3420 /*
3421  * Allocates new EVP_MD_CTX and sets pointer to it into given pointer
3422  * vairable, freeing EVP_MD_CTX previously stored in that variable, if any.
3423  * If EVP_MD pointer is passed, initializes ctx with this md Returns newly
3424  * allocated ctx;
3425  */
3426
3427 EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
3428 {
3429     ssl_clear_hash_ctx(hash);
3430     *hash = EVP_MD_CTX_create();
3431     if (md)
3432         EVP_DigestInit_ex(*hash, md, NULL);
3433     return *hash;
3434 }
3435
3436 void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
3437 {
3438
3439     if (*hash)
3440         EVP_MD_CTX_destroy(*hash);
3441     *hash = NULL;
3442 }
3443
3444 /* Retrieve handshake hashes */
3445 int ssl_handshake_hash(SSL *s, unsigned char *out, int outlen)
3446 {
3447     unsigned char *p = out;
3448     int idx, ret = 0;
3449     long mask;
3450     EVP_MD_CTX ctx;
3451     const EVP_MD *md;
3452     EVP_MD_CTX_init(&ctx);
3453     for (idx = 0; ssl_get_handshake_digest(idx, &mask, &md); idx++) {
3454         if (mask & ssl_get_algorithm2(s)) {
3455             int hashsize = EVP_MD_size(md);
3456             EVP_MD_CTX *hdgst = s->s3->handshake_dgst[idx];
3457             if (!hdgst || hashsize < 0 || hashsize > outlen)
3458                 goto err;
3459             if (!EVP_MD_CTX_copy_ex(&ctx, hdgst))
3460                 goto err;
3461             if (!EVP_DigestFinal_ex(&ctx, p, NULL))
3462                 goto err;
3463             p += hashsize;
3464             outlen -= hashsize;
3465         }
3466     }
3467     ret = p - out;
3468  err:
3469     EVP_MD_CTX_cleanup(&ctx);
3470     return ret;
3471 }
3472
3473 void SSL_set_debug(SSL *s, int debug)
3474 {
3475     s->debug = debug;
3476 }
3477
3478 int SSL_cache_hit(SSL *s)
3479 {
3480     return s->hit;
3481 }
3482
3483 int SSL_is_server(SSL *s)
3484 {
3485     return s->server;
3486 }
3487
3488 void SSL_set_security_level(SSL *s, int level)
3489 {
3490     s->cert->sec_level = level;
3491 }
3492
3493 int SSL_get_security_level(const SSL *s)
3494 {
3495     return s->cert->sec_level;
3496 }
3497
3498 void SSL_set_security_callback(SSL *s,
3499                                int (*cb) (SSL *s, SSL_CTX *ctx, int op,
3500                                           int bits, int nid, void *other,
3501                                           void *ex))
3502 {
3503     s->cert->sec_cb = cb;
3504 }
3505
3506 int (*SSL_get_security_callback(const SSL *s)) (SSL *s, SSL_CTX *ctx, int op,
3507                                                 int bits, int nid,
3508                                                 void *other, void *ex) {
3509     return s->cert->sec_cb;
3510 }
3511
3512 void SSL_set0_security_ex_data(SSL *s, void *ex)
3513 {
3514     s->cert->sec_ex = ex;
3515 }
3516
3517 void *SSL_get0_security_ex_data(const SSL *s)
3518 {
3519     return s->cert->sec_ex;
3520 }
3521
3522 void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
3523 {
3524     ctx->cert->sec_level = level;
3525 }
3526
3527 int SSL_CTX_get_security_level(const SSL_CTX *ctx)
3528 {
3529     return ctx->cert->sec_level;
3530 }
3531
3532 void SSL_CTX_set_security_callback(SSL_CTX *ctx,
3533                                    int (*cb) (SSL *s, SSL_CTX *ctx, int op,
3534                                               int bits, int nid, void *other,
3535                                               void *ex))
3536 {
3537     ctx->cert->sec_cb = cb;
3538 }
3539
3540 int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (SSL *s,
3541                                                           SSL_CTX *ctx,
3542                                                           int op, int bits,
3543                                                           int nid,
3544                                                           void *other,
3545                                                           void *ex) {
3546     return ctx->cert->sec_cb;
3547 }
3548
3549 void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
3550 {
3551     ctx->cert->sec_ex = ex;
3552 }
3553
3554 void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
3555 {
3556     return ctx->cert->sec_ex;
3557 }
3558
3559 IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);