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