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