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