ssl_lib.c revision 1.41
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
778(*SSL_get_verify_callback(const SSL *s))(int, X509_STORE_CTX *)
779{
780	return (s->verify_callback);
781}
782
783int
784SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
785{
786	return (ctx->verify_mode);
787}
788
789int
790SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
791{
792	return (X509_VERIFY_PARAM_get_depth(ctx->param));
793}
794
795int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))(int, X509_STORE_CTX *)
796{
797	return (ctx->default_verify_callback);
798}
799
800void
801SSL_set_verify(SSL *s, int mode,
802    int (*callback)(int ok, X509_STORE_CTX *ctx))
803{
804	s->verify_mode = mode;
805	if (callback != NULL)
806		s->verify_callback = callback;
807}
808
809void
810SSL_set_verify_depth(SSL *s, int depth)
811{
812	X509_VERIFY_PARAM_set_depth(s->param, depth);
813}
814
815void
816SSL_set_read_ahead(SSL *s, int yes)
817{
818	s->read_ahead = yes;
819}
820
821int
822SSL_get_read_ahead(const SSL *s)
823{
824	return (s->read_ahead);
825}
826
827int
828SSL_pending(const SSL *s)
829{
830	/*
831	 * SSL_pending cannot work properly if read-ahead is enabled
832	 * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)),
833	 * and it is impossible to fix since SSL_pending cannot report
834	 * errors that may be observed while scanning the new data.
835	 * (Note that SSL_pending() is often used as a boolean value,
836	 * so we'd better not return -1.)
837	 */
838	return (s->method->ssl_pending(s));
839}
840
841X509 *
842SSL_get_peer_certificate(const SSL *s)
843{
844	X509	*r;
845
846	if ((s == NULL) || (s->session == NULL))
847		r = NULL;
848	else
849		r = s->session->peer;
850
851	if (r == NULL)
852		return (r);
853
854	CRYPTO_add(&r->references, 1, CRYPTO_LOCK_X509);
855
856	return (r);
857}
858
859STACK_OF(X509) *
860SSL_get_peer_cert_chain(const SSL *s)
861{
862	STACK_OF(X509)	*r;
863
864	if ((s == NULL) || (s->session == NULL) ||
865	    (s->session->sess_cert == NULL))
866		r = NULL;
867	else
868		r = s->session->sess_cert->cert_chain;
869
870	/*
871	 * If we are a client, cert_chain includes the peer's own
872	 * certificate;
873	 * if we are a server, it does not.
874	 */
875	return (r);
876}
877
878/*
879 * Now in theory, since the calling process own 't' it should be safe to
880 * modify.  We need to be able to read f without being hassled
881 */
882void
883SSL_copy_session_id(SSL *t, const SSL *f)
884{
885	CERT	*tmp;
886
887	/* Do we need to to SSL locking? */
888	SSL_set_session(t, SSL_get_session(f));
889
890	/*
891	 * What if we are setup as SSLv2 but want to talk SSLv3 or
892	 * vice-versa.
893	 */
894	if (t->method != f->method) {
895		t->method->ssl_free(t);	/* cleanup current */
896		t->method=f->method;	/* change method */
897		t->method->ssl_new(t);	/* setup new */
898	}
899
900	tmp = t->cert;
901	if (f->cert != NULL) {
902		CRYPTO_add(&f->cert->references, 1, CRYPTO_LOCK_SSL_CERT);
903		t->cert = f->cert;
904	} else
905		t->cert = NULL;
906	if (tmp != NULL)
907		ssl_cert_free(tmp);
908	SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length);
909}
910
911/* Fix this so it checks all the valid key/cert options */
912int
913SSL_CTX_check_private_key(const SSL_CTX *ctx)
914{
915	if ((ctx == NULL) || (ctx->cert == NULL) ||
916	    (ctx->cert->key->x509 == NULL)) {
917		SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
918		    SSL_R_NO_CERTIFICATE_ASSIGNED);
919		return (0);
920	}
921	if (ctx->cert->key->privatekey == NULL) {
922		SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
923		    SSL_R_NO_PRIVATE_KEY_ASSIGNED);
924		return (0);
925	}
926	return (X509_check_private_key(ctx->cert->key->x509,
927	    ctx->cert->key->privatekey));
928}
929
930/* Fix this function so that it takes an optional type parameter */
931int
932SSL_check_private_key(const SSL *ssl)
933{
934	if (ssl == NULL) {
935		SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,
936		    ERR_R_PASSED_NULL_PARAMETER);
937		return (0);
938	}
939	if (ssl->cert == NULL) {
940		SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,
941		    SSL_R_NO_CERTIFICATE_ASSIGNED);
942		return (0);
943	}
944	if (ssl->cert->key->x509 == NULL) {
945		SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,
946		    SSL_R_NO_CERTIFICATE_ASSIGNED);
947		return (0);
948	}
949	if (ssl->cert->key->privatekey == NULL) {
950		SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY,
951		    SSL_R_NO_PRIVATE_KEY_ASSIGNED);
952		return (0);
953	}
954	return (X509_check_private_key(ssl->cert->key->x509,
955	    ssl->cert->key->privatekey));
956}
957
958int
959SSL_accept(SSL *s)
960{
961	if (s->handshake_func == 0)
962		SSL_set_accept_state(s); /* Not properly initialized yet */
963
964	return (s->method->ssl_accept(s));
965}
966
967int
968SSL_connect(SSL *s)
969{
970	if (s->handshake_func == 0)
971		SSL_set_connect_state(s); /* Not properly initialized yet */
972
973	return (s->method->ssl_connect(s));
974}
975
976long
977SSL_get_default_timeout(const SSL *s)
978{
979	return (s->method->get_timeout());
980}
981
982int
983SSL_read(SSL *s, void *buf, int num)
984{
985	if (s->handshake_func == 0) {
986		SSLerr(SSL_F_SSL_READ,
987		    SSL_R_UNINITIALIZED);
988		return (-1);
989	}
990
991	if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
992		s->rwstate = SSL_NOTHING;
993		return (0);
994	}
995	return (s->method->ssl_read(s, buf, num));
996}
997
998int
999SSL_peek(SSL *s, void *buf, int num)
1000{
1001	if (s->handshake_func == 0) {
1002		SSLerr(SSL_F_SSL_PEEK,
1003		    SSL_R_UNINITIALIZED);
1004		return (-1);
1005	}
1006
1007	if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1008		return (0);
1009	}
1010	return (s->method->ssl_peek(s, buf, num));
1011}
1012
1013int
1014SSL_write(SSL *s, const void *buf, int num)
1015{
1016	if (s->handshake_func == 0) {
1017		SSLerr(SSL_F_SSL_WRITE,
1018		    SSL_R_UNINITIALIZED);
1019		return (-1);
1020	}
1021
1022	if (s->shutdown & SSL_SENT_SHUTDOWN) {
1023		s->rwstate = SSL_NOTHING;
1024		SSLerr(SSL_F_SSL_WRITE,
1025		    SSL_R_PROTOCOL_IS_SHUTDOWN);
1026		return (-1);
1027	}
1028	return (s->method->ssl_write(s, buf, num));
1029}
1030
1031int
1032SSL_shutdown(SSL *s)
1033{
1034	/*
1035	 * Note that this function behaves differently from what one might
1036	 * expect.  Return values are 0 for no success (yet),
1037	 * 1 for success; but calling it once is usually not enough,
1038	 * even if blocking I/O is used (see ssl3_shutdown).
1039	 */
1040
1041	if (s->handshake_func == 0) {
1042		SSLerr(SSL_F_SSL_SHUTDOWN,
1043		    SSL_R_UNINITIALIZED);
1044		return (-1);
1045	}
1046
1047	if ((s != NULL) && !SSL_in_init(s))
1048		return (s->method->ssl_shutdown(s));
1049	else
1050		return (1);
1051}
1052
1053int
1054SSL_renegotiate(SSL *s)
1055{
1056	if (s->renegotiate == 0)
1057		s->renegotiate = 1;
1058
1059	s->new_session = 1;
1060
1061	return (s->method->ssl_renegotiate(s));
1062}
1063
1064int
1065SSL_renegotiate_abbreviated(SSL *s)
1066{
1067	if (s->renegotiate == 0)
1068		s->renegotiate = 1;
1069
1070	s->new_session = 0;
1071
1072	return (s->method->ssl_renegotiate(s));
1073}
1074
1075int
1076SSL_renegotiate_pending(SSL *s)
1077{
1078	/*
1079	 * Becomes true when negotiation is requested;
1080	 * false again once a handshake has finished.
1081	 */
1082	return (s->renegotiate != 0);
1083}
1084
1085long
1086SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
1087{
1088	long	l;
1089
1090	switch (cmd) {
1091	case SSL_CTRL_GET_READ_AHEAD:
1092		return (s->read_ahead);
1093	case SSL_CTRL_SET_READ_AHEAD:
1094		l = s->read_ahead;
1095		s->read_ahead = larg;
1096		return (l);
1097
1098	case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1099		s->msg_callback_arg = parg;
1100		return (1);
1101
1102	case SSL_CTRL_OPTIONS:
1103		return (s->options|=larg);
1104	case SSL_CTRL_CLEAR_OPTIONS:
1105		return (s->options&=~larg);
1106	case SSL_CTRL_MODE:
1107		return (s->mode|=larg);
1108	case SSL_CTRL_CLEAR_MODE:
1109		return (s->mode &=~larg);
1110	case SSL_CTRL_GET_MAX_CERT_LIST:
1111		return (s->max_cert_list);
1112	case SSL_CTRL_SET_MAX_CERT_LIST:
1113		l = s->max_cert_list;
1114		s->max_cert_list = larg;
1115		return (l);
1116	case SSL_CTRL_SET_MTU:
1117#ifndef OPENSSL_NO_DTLS1
1118		if (larg < (long)dtls1_min_mtu())
1119			return (0);
1120#endif
1121
1122		if (SSL_version(s) == DTLS1_VERSION ||
1123		    SSL_version(s) == DTLS1_BAD_VER) {
1124			s->d1->mtu = larg;
1125			return (larg);
1126		}
1127		return (0);
1128	case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1129		if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1130			return (0);
1131		s->max_send_fragment = larg;
1132		return (1);
1133	case SSL_CTRL_GET_RI_SUPPORT:
1134		if (s->s3)
1135			return (s->s3->send_connection_binding);
1136		else return (0);
1137	default:
1138		return (s->method->ssl_ctrl(s, cmd, larg, parg));
1139	}
1140}
1141
1142long
1143SSL_callback_ctrl(SSL *s, int cmd, void (*fp)(void))
1144{
1145	switch (cmd) {
1146	case SSL_CTRL_SET_MSG_CALLBACK:
1147		s->msg_callback = (void (*)(int write_p, int version,
1148		    int content_type, const void *buf, size_t len,
1149		    SSL *ssl, void *arg))(fp);
1150		return (1);
1151
1152	default:
1153		return (s->method->ssl_callback_ctrl(s, cmd, fp));
1154	}
1155}
1156
1157LHASH_OF(SSL_SESSION) *
1158SSL_CTX_sessions(SSL_CTX *ctx)
1159{
1160	return (ctx->sessions);
1161}
1162
1163long
1164SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
1165{
1166	long	l;
1167
1168	switch (cmd) {
1169	case SSL_CTRL_GET_READ_AHEAD:
1170		return (ctx->read_ahead);
1171	case SSL_CTRL_SET_READ_AHEAD:
1172		l = ctx->read_ahead;
1173		ctx->read_ahead = larg;
1174		return (l);
1175
1176	case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1177		ctx->msg_callback_arg = parg;
1178		return (1);
1179
1180	case SSL_CTRL_GET_MAX_CERT_LIST:
1181		return (ctx->max_cert_list);
1182	case SSL_CTRL_SET_MAX_CERT_LIST:
1183		l = ctx->max_cert_list;
1184		ctx->max_cert_list = larg;
1185		return (l);
1186
1187	case SSL_CTRL_SET_SESS_CACHE_SIZE:
1188		l = ctx->session_cache_size;
1189		ctx->session_cache_size = larg;
1190		return (l);
1191	case SSL_CTRL_GET_SESS_CACHE_SIZE:
1192		return (ctx->session_cache_size);
1193	case SSL_CTRL_SET_SESS_CACHE_MODE:
1194		l = ctx->session_cache_mode;
1195		ctx->session_cache_mode = larg;
1196		return (l);
1197	case SSL_CTRL_GET_SESS_CACHE_MODE:
1198		return (ctx->session_cache_mode);
1199
1200	case SSL_CTRL_SESS_NUMBER:
1201		return (lh_SSL_SESSION_num_items(ctx->sessions));
1202	case SSL_CTRL_SESS_CONNECT:
1203		return (ctx->stats.sess_connect);
1204	case SSL_CTRL_SESS_CONNECT_GOOD:
1205		return (ctx->stats.sess_connect_good);
1206	case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
1207		return (ctx->stats.sess_connect_renegotiate);
1208	case SSL_CTRL_SESS_ACCEPT:
1209		return (ctx->stats.sess_accept);
1210	case SSL_CTRL_SESS_ACCEPT_GOOD:
1211		return (ctx->stats.sess_accept_good);
1212	case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
1213		return (ctx->stats.sess_accept_renegotiate);
1214	case SSL_CTRL_SESS_HIT:
1215		return (ctx->stats.sess_hit);
1216	case SSL_CTRL_SESS_CB_HIT:
1217		return (ctx->stats.sess_cb_hit);
1218	case SSL_CTRL_SESS_MISSES:
1219		return (ctx->stats.sess_miss);
1220	case SSL_CTRL_SESS_TIMEOUTS:
1221		return (ctx->stats.sess_timeout);
1222	case SSL_CTRL_SESS_CACHE_FULL:
1223		return (ctx->stats.sess_cache_full);
1224	case SSL_CTRL_OPTIONS:
1225		return (ctx->options|=larg);
1226	case SSL_CTRL_CLEAR_OPTIONS:
1227		return (ctx->options&=~larg);
1228	case SSL_CTRL_MODE:
1229		return (ctx->mode|=larg);
1230	case SSL_CTRL_CLEAR_MODE:
1231		return (ctx->mode&=~larg);
1232	case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1233		if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1234			return (0);
1235		ctx->max_send_fragment = larg;
1236		return (1);
1237	default:
1238		return (ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg));
1239	}
1240}
1241
1242long
1243SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp)(void))
1244{
1245	switch (cmd) {
1246	case SSL_CTRL_SET_MSG_CALLBACK:
1247		ctx->msg_callback = (void (*)(int write_p, int version,
1248		    int content_type, const void *buf, size_t len, SSL *ssl,
1249		    void *arg))(fp);
1250		return (1);
1251
1252	default:
1253		return (ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp));
1254	}
1255}
1256
1257int
1258ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
1259{
1260	long	l;
1261
1262	l = a->id - b->id;
1263	if (l == 0L)
1264		return (0);
1265	else
1266		return ((l > 0) ? 1:-1);
1267}
1268
1269int
1270ssl_cipher_ptr_id_cmp(const SSL_CIPHER * const *ap,
1271    const SSL_CIPHER * const *bp)
1272{
1273	long	l;
1274
1275	l = (*ap)->id - (*bp)->id;
1276	if (l == 0L)
1277		return (0);
1278	else
1279		return ((l > 0) ? 1:-1);
1280}
1281
1282/*
1283 * Return a STACK of the ciphers available for the SSL and in order of
1284 * preference.
1285 */
1286STACK_OF(SSL_CIPHER) *
1287SSL_get_ciphers(const SSL *s)
1288{
1289	if (s != NULL) {
1290		if (s->cipher_list != NULL) {
1291			return (s->cipher_list);
1292		} else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
1293			return (s->ctx->cipher_list);
1294		}
1295	}
1296	return (NULL);
1297}
1298
1299/*
1300 * Return a STACK of the ciphers available for the SSL and in order of
1301 * algorithm id.
1302 */
1303STACK_OF(SSL_CIPHER) *
1304ssl_get_ciphers_by_id(SSL *s)
1305{
1306	if (s != NULL) {
1307		if (s->cipher_list_by_id != NULL) {
1308			return (s->cipher_list_by_id);
1309		} else if ((s->ctx != NULL) &&
1310		    (s->ctx->cipher_list_by_id != NULL)) {
1311			return (s->ctx->cipher_list_by_id);
1312		}
1313	}
1314	return (NULL);
1315}
1316
1317/* The old interface to get the same thing as SSL_get_ciphers(). */
1318const char *
1319SSL_get_cipher_list(const SSL *s, int n)
1320{
1321	SSL_CIPHER		*c;
1322	STACK_OF(SSL_CIPHER)	*sk;
1323
1324	if (s == NULL)
1325		return (NULL);
1326	sk = SSL_get_ciphers(s);
1327	if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
1328		return (NULL);
1329	c = sk_SSL_CIPHER_value(sk, n);
1330	if (c == NULL)
1331		return (NULL);
1332	return (c->name);
1333}
1334
1335/* Specify the ciphers to be used by default by the SSL_CTX. */
1336int
1337SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
1338{
1339	STACK_OF(SSL_CIPHER)	*sk;
1340
1341	sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
1342	    &ctx->cipher_list_by_id, str);
1343	/*
1344	 * ssl_create_cipher_list may return an empty stack if it
1345	 * was unable to find a cipher matching the given rule string
1346	 * (for example if the rule string specifies a cipher which
1347	 * has been disabled). This is not an error as far as
1348	 * ssl_create_cipher_list is concerned, and hence
1349	 * ctx->cipher_list and ctx->cipher_list_by_id has been
1350	 * updated.
1351	 */
1352	if (sk == NULL)
1353		return (0);
1354	else if (sk_SSL_CIPHER_num(sk) == 0) {
1355		SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST,
1356		    SSL_R_NO_CIPHER_MATCH);
1357		return (0);
1358	}
1359	return (1);
1360}
1361
1362/* Specify the ciphers to be used by the SSL. */
1363int
1364SSL_set_cipher_list(SSL *s, const char *str)
1365{
1366	STACK_OF(SSL_CIPHER)	*sk;
1367
1368	sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
1369	&s->cipher_list_by_id, str);
1370	/* see comment in SSL_CTX_set_cipher_list */
1371	if (sk == NULL)
1372		return (0);
1373	else if (sk_SSL_CIPHER_num(sk) == 0) {
1374		SSLerr(SSL_F_SSL_SET_CIPHER_LIST,
1375		    SSL_R_NO_CIPHER_MATCH);
1376		return (0);
1377	}
1378	return (1);
1379}
1380
1381/* works well for SSLv2, not so good for SSLv3 */
1382char *
1383SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
1384{
1385	char			*end;
1386	STACK_OF(SSL_CIPHER)	*sk;
1387	SSL_CIPHER		*c;
1388	size_t			 curlen = 0;
1389	int			 i;
1390
1391	if ((s->session == NULL) || (s->session->ciphers == NULL) ||
1392		(len < 2))
1393	return (NULL);
1394
1395	sk = s->session->ciphers;
1396	buf[0] = '\0';
1397	for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1398		c = sk_SSL_CIPHER_value(sk, i);
1399		end = buf + curlen;
1400		if (strlcat(buf, c->name, len) >= len ||
1401		    (curlen = strlcat(buf, ":", len)) >= len) {
1402			/* remove truncated cipher from list */
1403			*end = '\0';
1404			break;
1405		}
1406	}
1407	/* remove trailing colon */
1408	if ((end = strrchr(buf, ':')) != NULL)
1409		*end = '\0';
1410	return (buf);
1411}
1412
1413int
1414ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk, unsigned char *p,
1415    int (*put_cb)(const SSL_CIPHER *, unsigned char *))
1416{
1417	int		 i, j = 0;
1418	SSL_CIPHER	*c;
1419	unsigned char	*q;
1420#ifndef OPENSSL_NO_KRB5
1421	int		 nokrb5 = !kssl_tgt_is_available(s->kssl_ctx);
1422#endif /* OPENSSL_NO_KRB5 */
1423
1424	if (sk == NULL)
1425		return (0);
1426	q = p;
1427
1428	for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1429		c = sk_SSL_CIPHER_value(sk, i);
1430		/* Skip TLS v1.2 only ciphersuites if lower than v1.2 */
1431		if ((c->algorithm_ssl & SSL_TLSV1_2) &&
1432		    (TLS1_get_client_version(s) < TLS1_2_VERSION))
1433			continue;
1434#ifndef OPENSSL_NO_KRB5
1435		if (((c->algorithm_mkey & SSL_kKRB5) ||
1436		    (c->algorithm_auth & SSL_aKRB5)) && nokrb5)
1437			continue;
1438#endif /* OPENSSL_NO_KRB5 */
1439#ifndef OPENSSL_NO_PSK
1440		/* with PSK there must be client callback set */
1441		if (((c->algorithm_mkey & SSL_kPSK) ||
1442		    (c->algorithm_auth & SSL_aPSK)) &&
1443		    s->psk_client_callback == NULL)
1444			continue;
1445#endif /* OPENSSL_NO_PSK */
1446		j = put_cb ? put_cb(c, p) : ssl_put_cipher_by_char(s, c, p);
1447		p += j;
1448	}
1449	/*
1450	 * If p == q, no ciphers and caller indicates an error. Otherwise
1451	 * add SCSV if not renegotiating.
1452	 */
1453	if (p != q && !s->renegotiate) {
1454		static SSL_CIPHER scsv = {
1455			0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
1456		};
1457		j = put_cb ? put_cb(&scsv, p) :
1458		    ssl_put_cipher_by_char(s, &scsv, p);
1459		p += j;
1460#ifdef OPENSSL_RI_DEBUG
1461		fprintf(stderr, "SCSV sent by client\n");
1462#endif
1463	}
1464
1465	return (p - q);
1466}
1467
1468STACK_OF(SSL_CIPHER) *
1469ssl_bytes_to_cipher_list(SSL *s, unsigned char *p, int num,
1470    STACK_OF(SSL_CIPHER) **skp)
1471{
1472	const SSL_CIPHER	*c;
1473	STACK_OF(SSL_CIPHER)	*sk;
1474	int			 i, n;
1475
1476	if (s->s3)
1477		s->s3->send_connection_binding = 0;
1478
1479	n = ssl_put_cipher_by_char(s, NULL, NULL);
1480	if ((num % n) != 0) {
1481		SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
1482		    SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
1483		return (NULL);
1484	}
1485	if ((skp == NULL) || (*skp == NULL))
1486		sk=sk_SSL_CIPHER_new_null(); /* change perhaps later */
1487	else {
1488		sk= *skp;
1489		sk_SSL_CIPHER_zero(sk);
1490	}
1491
1492	for (i = 0; i < num; i += n) {
1493		/* Check for SCSV */
1494		if (s->s3 && (n != 3 || !p[0]) &&
1495		    (p[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
1496		    (p[n - 1] == (SSL3_CK_SCSV & 0xff))) {
1497			/* SCSV fatal if renegotiating */
1498			if (s->renegotiate) {
1499				SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
1500				    SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1501				ssl3_send_alert(s, SSL3_AL_FATAL,
1502				    SSL_AD_HANDSHAKE_FAILURE);
1503
1504				goto err;
1505			}
1506			s->s3->send_connection_binding = 1;
1507			p += n;
1508#ifdef OPENSSL_RI_DEBUG
1509			fprintf(stderr, "SCSV received by server\n");
1510#endif
1511			continue;
1512		}
1513
1514		c = ssl_get_cipher_by_char(s, p);
1515		p += n;
1516		if (c != NULL) {
1517			if (!sk_SSL_CIPHER_push(sk, c)) {
1518				SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
1519				    ERR_R_MALLOC_FAILURE);
1520				goto err;
1521			}
1522		}
1523	}
1524
1525	if (skp != NULL)
1526		*skp = sk;
1527	return (sk);
1528 err:
1529	if ((skp == NULL) || (*skp == NULL))
1530		sk_SSL_CIPHER_free(sk);
1531	return (NULL);
1532}
1533
1534
1535#ifndef OPENSSL_NO_TLSEXT
1536/*
1537 * Return a servername extension value if provided in Client Hello, or NULL.
1538 * So far, only host_name types are defined (RFC 3546).
1539 */
1540const char *
1541SSL_get_servername(const SSL *s, const int type)
1542{
1543	if (type != TLSEXT_NAMETYPE_host_name)
1544		return (NULL);
1545
1546	return (s->session && !s->tlsext_hostname ?
1547	    s->session->tlsext_hostname :
1548	    s->tlsext_hostname);
1549}
1550
1551int
1552SSL_get_servername_type(const SSL *s)
1553{
1554	if (s->session &&
1555	    (!s->tlsext_hostname ?
1556	    s->session->tlsext_hostname : s->tlsext_hostname))
1557		return (TLSEXT_NAMETYPE_host_name);
1558	return (-1);
1559}
1560
1561# ifndef OPENSSL_NO_NEXTPROTONEG
1562/*
1563 * SSL_select_next_proto implements the standard protocol selection. It is
1564 * expected that this function is called from the callback set by
1565 * SSL_CTX_set_next_proto_select_cb.
1566 *
1567 * The protocol data is assumed to be a vector of 8-bit, length prefixed byte
1568 * strings. The length byte itself is not included in the length. A byte
1569 * string of length 0 is invalid. No byte string may be truncated.
1570 *
1571 * The current, but experimental algorithm for selecting the protocol is:
1572 *
1573 * 1) If the server doesn't support NPN then this is indicated to the
1574 * callback. In this case, the client application has to abort the connection
1575 * or have a default application level protocol.
1576 *
1577 * 2) If the server supports NPN, but advertises an empty list then the
1578 * client selects the first protcol in its list, but indicates via the
1579 * API that this fallback case was enacted.
1580 *
1581 * 3) Otherwise, the client finds the first protocol in the server's list
1582 * that it supports and selects this protocol. This is because it's
1583 * assumed that the server has better information about which protocol
1584 * a client should use.
1585 *
1586 * 4) If the client doesn't support any of the server's advertised
1587 * protocols, then this is treated the same as case 2.
1588 *
1589 * It returns either
1590 * OPENSSL_NPN_NEGOTIATED if a common protocol was found, or
1591 * OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
1592 */
1593int
1594SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
1595    const unsigned char *server, unsigned int server_len,
1596    const unsigned char *client, unsigned int client_len)
1597{
1598	unsigned int		 i, j;
1599	const unsigned char	*result;
1600	int			 status = OPENSSL_NPN_UNSUPPORTED;
1601
1602	/*
1603	 * For each protocol in server preference order,
1604	 * see if we support it.
1605	 */
1606	for (i = 0; i < server_len; ) {
1607		for (j = 0; j < client_len; ) {
1608			if (server[i] == client[j] &&
1609			    memcmp(&server[i + 1],
1610			    &client[j + 1], server[i]) == 0) {
1611				/* We found a match */
1612				result = &server[i];
1613				status = OPENSSL_NPN_NEGOTIATED;
1614				goto found;
1615			}
1616			j += client[j];
1617			j++;
1618		}
1619		i += server[i];
1620		i++;
1621	}
1622
1623	/* There's no overlap between our protocols and the server's list. */
1624	result = client;
1625	status = OPENSSL_NPN_NO_OVERLAP;
1626
1627 found:
1628	*out = (unsigned char *) result + 1;
1629	*outlen = result[0];
1630	return (status);
1631}
1632
1633/*
1634 * SSL_get0_next_proto_negotiated sets *data and *len to point to the client's
1635 * requested protocol for this connection and returns 0. If the client didn't
1636 * request any protocol, then *data is set to NULL.
1637 *
1638 * Note that the client can request any protocol it chooses. The value returned
1639 * from this function need not be a member of the list of supported protocols
1640 * provided by the callback.
1641 */
1642void
1643SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
1644    unsigned *len)
1645{
1646	*data = s->next_proto_negotiated;
1647	if (!*data) {
1648		*len = 0;
1649	} else {
1650		*len = s->next_proto_negotiated_len;
1651	}
1652}
1653
1654/*
1655 * SSL_CTX_set_next_protos_advertised_cb sets a callback that is called when a
1656 * TLS server needs a list of supported protocols for Next Protocol
1657 * Negotiation. The returned list must be in wire format.  The list is returned
1658 * by setting |out| to point to it and |outlen| to its length. This memory will
1659 * not be modified, but one should assume that the SSL* keeps a reference to
1660 * it.
1661 *
1662 * The callback should return SSL_TLSEXT_ERR_OK if it wishes to advertise.
1663 * Otherwise, no such extension will be included in the ServerHello.
1664 */
1665void
1666SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx, int (*cb) (SSL *ssl,
1667    const unsigned char **out, unsigned int *outlen, void *arg), void *arg)
1668{
1669	ctx->next_protos_advertised_cb = cb;
1670	ctx->next_protos_advertised_cb_arg = arg;
1671}
1672
1673/*
1674 * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
1675 * client needs to select a protocol from the server's provided list. |out|
1676 * must be set to point to the selected protocol (which may be within |in|).
1677 * The length of the protocol name must be written into |outlen|. The server's
1678 * advertised protocols are provided in |in| and |inlen|. The callback can
1679 * assume that |in| is syntactically valid.
1680 *
1681 * The client must select a protocol. It is fatal to the connection if this
1682 * callback returns a value other than SSL_TLSEXT_ERR_OK.
1683 */
1684void
1685SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, int (*cb) (SSL *s,
1686    unsigned char **out, unsigned char *outlen, const unsigned char *in,
1687    unsigned int inlen, void *arg), void *arg)
1688{
1689	ctx->next_proto_select_cb = cb;
1690	ctx->next_proto_select_cb_arg = arg;
1691}
1692# endif
1693#endif
1694
1695int
1696SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1697    const char *label, size_t llen, const unsigned char *p, size_t plen,
1698    int use_context)
1699{
1700	if (s->version < TLS1_VERSION)
1701		return (-1);
1702
1703	return (s->method->ssl3_enc->export_keying_material(s, out, olen,
1704	    label, llen, p, plen, use_context));
1705}
1706
1707static unsigned long
1708ssl_session_hash(const SSL_SESSION *a)
1709{
1710	unsigned long	l;
1711
1712	l = (unsigned long)
1713	    ((unsigned int) a->session_id[0]     )|
1714	    ((unsigned int) a->session_id[1]<< 8L)|
1715	    ((unsigned long)a->session_id[2]<<16L)|
1716	    ((unsigned long)a->session_id[3]<<24L);
1717	return (l);
1718}
1719
1720/*
1721 * NB: If this function (or indeed the hash function which uses a sort of
1722 * coarser function than this one) is changed, ensure
1723 * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on being
1724 * able to construct an SSL_SESSION that will collide with any existing session
1725 * with a matching session ID.
1726 */
1727static int
1728ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
1729{
1730	if (a->ssl_version != b->ssl_version)
1731		return (1);
1732	if (a->session_id_length != b->session_id_length)
1733		return (1);
1734	return (memcmp(a->session_id, b->session_id, a->session_id_length));
1735}
1736
1737/*
1738 * These wrapper functions should remain rather than redeclaring
1739 * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
1740 * variable. The reason is that the functions aren't static, they're exposed via
1741 * ssl.h.
1742 */
1743static
1744IMPLEMENT_LHASH_HASH_FN(ssl_session, SSL_SESSION)
1745static
1746IMPLEMENT_LHASH_COMP_FN(ssl_session, SSL_SESSION)
1747
1748SSL_CTX *
1749SSL_CTX_new(const SSL_METHOD *meth)
1750{
1751	SSL_CTX	*ret = NULL;
1752
1753	if (meth == NULL) {
1754		SSLerr(SSL_F_SSL_CTX_NEW,
1755		    SSL_R_NULL_SSL_METHOD_PASSED);
1756		return (NULL);
1757	}
1758
1759	if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
1760		SSLerr(SSL_F_SSL_CTX_NEW,
1761		    SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
1762		goto err;
1763	}
1764	ret = calloc(1, sizeof(SSL_CTX));
1765	if (ret == NULL)
1766		goto err;
1767
1768	ret->method = meth;
1769
1770	ret->cert_store = NULL;
1771	ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
1772	ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
1773	ret->session_cache_head = NULL;
1774	ret->session_cache_tail = NULL;
1775
1776	/* We take the system default */
1777	ret->session_timeout = meth->get_timeout();
1778
1779	ret->new_session_cb = 0;
1780	ret->remove_session_cb = 0;
1781	ret->get_session_cb = 0;
1782	ret->generate_session_id = 0;
1783
1784	memset((char *)&ret->stats, 0, sizeof(ret->stats));
1785
1786	ret->references = 1;
1787	ret->quiet_shutdown = 0;
1788
1789/*	ret->cipher=NULL;
1790	ret->master_key=NULL;
1791*/
1792
1793	ret->info_callback = NULL;
1794
1795	ret->app_verify_callback = 0;
1796	ret->app_verify_arg = NULL;
1797
1798	ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
1799	ret->read_ahead = 0;
1800	ret->msg_callback = 0;
1801	ret->msg_callback_arg = NULL;
1802	ret->verify_mode = SSL_VERIFY_NONE;
1803#if 0
1804	ret->verify_depth=-1; /* Don't impose a limit (but x509_lu.c does) */
1805#endif
1806	ret->sid_ctx_length = 0;
1807	ret->default_verify_callback = NULL;
1808	if ((ret->cert = ssl_cert_new()) == NULL)
1809		goto err;
1810
1811	ret->default_passwd_callback = 0;
1812	ret->default_passwd_callback_userdata = NULL;
1813	ret->client_cert_cb = 0;
1814	ret->app_gen_cookie_cb = 0;
1815	ret->app_verify_cookie_cb = 0;
1816
1817	ret->sessions = lh_SSL_SESSION_new();
1818	if (ret->sessions == NULL)
1819		goto err;
1820	ret->cert_store = X509_STORE_new();
1821	if (ret->cert_store == NULL)
1822		goto err;
1823
1824	ssl_create_cipher_list(ret->method, &ret->cipher_list,
1825	    &ret->cipher_list_by_id, SSL_DEFAULT_CIPHER_LIST);
1826	if (ret->cipher_list == NULL ||
1827	    sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
1828		SSLerr(SSL_F_SSL_CTX_NEW,
1829		    SSL_R_LIBRARY_HAS_NO_CIPHERS);
1830		goto err2;
1831	}
1832
1833	ret->param = X509_VERIFY_PARAM_new();
1834	if (!ret->param)
1835		goto err;
1836
1837	if ((ret->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
1838		SSLerr(SSL_F_SSL_CTX_NEW,
1839		    SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
1840		goto err2;
1841	}
1842	if ((ret->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
1843		SSLerr(SSL_F_SSL_CTX_NEW,
1844		    SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
1845		goto err2;
1846	}
1847
1848	if ((ret->client_CA = sk_X509_NAME_new_null()) == NULL)
1849		goto err;
1850
1851	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data);
1852
1853	ret->extra_certs = NULL;
1854	/* No compression for DTLS */
1855	if (meth->version != DTLS1_VERSION)
1856		ret->comp_methods = SSL_COMP_get_compression_methods();
1857
1858	ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1859
1860#ifndef OPENSSL_NO_TLSEXT
1861	ret->tlsext_servername_callback = 0;
1862	ret->tlsext_servername_arg = NULL;
1863	/* Setup RFC4507 ticket keys */
1864	if ((RAND_pseudo_bytes(ret->tlsext_tick_key_name, 16) <= 0)
1865	    || (RAND_bytes(ret->tlsext_tick_hmac_key, 16) <= 0)
1866	    || (RAND_bytes(ret->tlsext_tick_aes_key, 16) <= 0))
1867		ret->options |= SSL_OP_NO_TICKET;
1868
1869	ret->tlsext_status_cb = 0;
1870	ret->tlsext_status_arg = NULL;
1871
1872# ifndef OPENSSL_NO_NEXTPROTONEG
1873	ret->next_protos_advertised_cb = 0;
1874	ret->next_proto_select_cb = 0;
1875# endif
1876#endif
1877#ifndef OPENSSL_NO_PSK
1878	ret->psk_identity_hint = NULL;
1879	ret->psk_client_callback = NULL;
1880	ret->psk_server_callback = NULL;
1881#endif
1882#ifndef OPENSSL_NO_SRP
1883	SSL_CTX_SRP_CTX_init(ret);
1884#endif
1885#ifndef OPENSSL_NO_ENGINE
1886	ret->client_cert_engine = NULL;
1887#ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
1888#define eng_strx(x)	#x
1889#define eng_str(x)	eng_strx(x)
1890	/* Use specific client engine automatically... ignore errors */
1891	{
1892		ENGINE *eng;
1893		eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1894		if (!eng) {
1895			ERR_clear_error();
1896			ENGINE_load_builtin_engines();
1897			eng = ENGINE_by_id(eng_str(
1898			    OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1899		}
1900		if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
1901			ERR_clear_error();
1902	}
1903#endif
1904#endif
1905	/*
1906	 * Default is to connect to non-RI servers. When RI is more widely
1907	 * deployed might change this.
1908	 */
1909	ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
1910
1911	return (ret);
1912 err:
1913	SSLerr(SSL_F_SSL_CTX_NEW,
1914	    ERR_R_MALLOC_FAILURE);
1915 err2:
1916	if (ret != NULL)
1917		SSL_CTX_free(ret);
1918	return (NULL);
1919}
1920
1921#if 0
1922static void
1923SSL_COMP_free(SSL_COMP *comp)
1924	{ free(comp);
1925}
1926#endif
1927
1928void
1929SSL_CTX_free(SSL_CTX *a)
1930{
1931	int	i;
1932
1933	if (a == NULL)
1934		return;
1935
1936	i = CRYPTO_add(&a->references, -1, CRYPTO_LOCK_SSL_CTX);
1937	if (i > 0)
1938		return;
1939
1940	if (a->param)
1941		X509_VERIFY_PARAM_free(a->param);
1942
1943	/*
1944	 * Free internal session cache. However: the remove_cb() may reference
1945	 * the ex_data of SSL_CTX, thus the ex_data store can only be removed
1946	 * after the sessions were flushed.
1947	 * As the ex_data handling routines might also touch the session cache,
1948	 * the most secure solution seems to be: empty (flush) the cache, then
1949	 * free ex_data, then finally free the cache.
1950	 * (See ticket [openssl.org #212].)
1951	 */
1952	if (a->sessions != NULL)
1953		SSL_CTX_flush_sessions(a, 0);
1954
1955	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
1956
1957	if (a->sessions != NULL)
1958		lh_SSL_SESSION_free(a->sessions);
1959
1960	if (a->cert_store != NULL)
1961		X509_STORE_free(a->cert_store);
1962	if (a->cipher_list != NULL)
1963		sk_SSL_CIPHER_free(a->cipher_list);
1964	if (a->cipher_list_by_id != NULL)
1965		sk_SSL_CIPHER_free(a->cipher_list_by_id);
1966	if (a->cert != NULL)
1967		ssl_cert_free(a->cert);
1968	if (a->client_CA != NULL)
1969		sk_X509_NAME_pop_free(a->client_CA, X509_NAME_free);
1970	if (a->extra_certs != NULL)
1971		sk_X509_pop_free(a->extra_certs, X509_free);
1972#if 0 /* This should never be done, since it removes a global database */
1973	if (a->comp_methods != NULL)
1974		sk_SSL_COMP_pop_free(a->comp_methods, SSL_COMP_free);
1975#else
1976	a->comp_methods = NULL;
1977#endif
1978
1979#ifndef OPENSSL_NO_SRTP
1980	if (a->srtp_profiles)
1981		sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
1982#endif
1983
1984#ifndef OPENSSL_NO_PSK
1985	if (a->psk_identity_hint)
1986		free(a->psk_identity_hint);
1987#endif
1988#ifndef OPENSSL_NO_SRP
1989	SSL_CTX_SRP_CTX_free(a);
1990#endif
1991#ifndef OPENSSL_NO_ENGINE
1992	if (a->client_cert_engine)
1993		ENGINE_finish(a->client_cert_engine);
1994#endif
1995
1996	free(a);
1997}
1998
1999void
2000SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2001{
2002	ctx->default_passwd_callback = cb;
2003}
2004
2005void
2006SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2007{
2008	ctx->default_passwd_callback_userdata = u;
2009}
2010
2011void
2012SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, int (*cb)(X509_STORE_CTX *,
2013    void *), void *arg)
2014{
2015	ctx->app_verify_callback = cb;
2016	ctx->app_verify_arg = arg;
2017}
2018
2019void
2020SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*cb)(int, X509_STORE_CTX *))
2021{
2022	ctx->verify_mode = mode;
2023	ctx->default_verify_callback = cb;
2024}
2025
2026void
2027SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
2028{
2029	X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2030}
2031
2032void
2033ssl_set_cert_masks(CERT *c, const SSL_CIPHER *cipher)
2034{
2035	CERT_PKEY	*cpk;
2036	int		 rsa_enc, rsa_tmp, rsa_sign, dh_tmp, dh_rsa, dh_dsa, dsa_sign;
2037	int		 rsa_enc_export, dh_rsa_export, dh_dsa_export;
2038	int		 rsa_tmp_export, dh_tmp_export, kl;
2039	unsigned long	 mask_k, mask_a, emask_k, emask_a;
2040	int		 have_ecc_cert, ecdh_ok, ecdsa_ok, ecc_pkey_size;
2041#ifndef OPENSSL_NO_ECDH
2042	int		 have_ecdh_tmp;
2043#endif
2044	X509		*x = NULL;
2045	EVP_PKEY	*ecc_pkey = NULL;
2046	int		 signature_nid = 0, pk_nid = 0, md_nid = 0;
2047
2048	if (c == NULL)
2049		return;
2050
2051	kl = SSL_C_EXPORT_PKEYLENGTH(cipher);
2052
2053	rsa_tmp = (c->rsa_tmp != NULL || c->rsa_tmp_cb != NULL);
2054	rsa_tmp_export = (c->rsa_tmp_cb != NULL ||
2055	(rsa_tmp && RSA_size(c->rsa_tmp)*8 <= kl));
2056#ifndef OPENSSL_NO_DH
2057	dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL);
2058	dh_tmp_export = (c->dh_tmp_cb != NULL ||
2059	(dh_tmp && DH_size(c->dh_tmp)*8 <= kl));
2060#else
2061	dh_tmp = dh_tmp_export = 0;
2062#endif
2063
2064#ifndef OPENSSL_NO_ECDH
2065	have_ecdh_tmp = (c->ecdh_tmp != NULL || c->ecdh_tmp_cb != NULL);
2066#endif
2067	cpk = &(c->pkeys[SSL_PKEY_RSA_ENC]);
2068	rsa_enc = (cpk->x509 != NULL && cpk->privatekey != NULL);
2069	rsa_enc_export = (rsa_enc && EVP_PKEY_size(cpk->privatekey)*8 <= kl);
2070	cpk = &(c->pkeys[SSL_PKEY_RSA_SIGN]);
2071	rsa_sign = (cpk->x509 != NULL && cpk->privatekey != NULL);
2072	cpk = &(c->pkeys[SSL_PKEY_DSA_SIGN]);
2073	dsa_sign = (cpk->x509 != NULL && cpk->privatekey != NULL);
2074	cpk = &(c->pkeys[SSL_PKEY_DH_RSA]);
2075	dh_rsa = (cpk->x509 != NULL && cpk->privatekey != NULL);
2076	dh_rsa_export = (dh_rsa && EVP_PKEY_size(cpk->privatekey)*8 <= kl);
2077	cpk = &(c->pkeys[SSL_PKEY_DH_DSA]);
2078/* FIX THIS EAY EAY EAY */
2079	dh_dsa = (cpk->x509 != NULL && cpk->privatekey != NULL);
2080	dh_dsa_export = (dh_dsa && EVP_PKEY_size(cpk->privatekey)*8 <= kl);
2081	cpk = &(c->pkeys[SSL_PKEY_ECC]);
2082	have_ecc_cert = (cpk->x509 != NULL && cpk->privatekey != NULL);
2083	mask_k = 0;
2084	mask_a = 0;
2085	emask_k = 0;
2086	emask_a = 0;
2087
2088
2089
2090#ifdef CIPHER_DEBUG
2091	printf("rt=%d rte=%d dht=%d ecdht=%d re=%d ree=%d "
2092	    "rs=%d ds=%d dhr=%d dhd=%d\n",
2093	    rsa_tmp, rsa_tmp_export, dh_tmp, have_ecdh_tmp,
2094	    rsa_enc, rsa_enc_export, rsa_sign, dsa_sign, dh_rsa, dh_dsa);
2095#endif
2096
2097	cpk = &(c->pkeys[SSL_PKEY_GOST01]);
2098	if (cpk->x509 != NULL && cpk->privatekey !=NULL) {
2099		mask_k |= SSL_kGOST;
2100		mask_a |= SSL_aGOST01;
2101	}
2102	cpk = &(c->pkeys[SSL_PKEY_GOST94]);
2103	if (cpk->x509 != NULL && cpk->privatekey !=NULL) {
2104		mask_k |= SSL_kGOST;
2105		mask_a |= SSL_aGOST94;
2106	}
2107
2108	if (rsa_enc || (rsa_tmp && rsa_sign))
2109		mask_k|=SSL_kRSA;
2110	if (rsa_enc_export || (rsa_tmp_export && (rsa_sign || rsa_enc)))
2111		emask_k|=SSL_kRSA;
2112
2113#if 0
2114	/* The match needs to be both kEDH and aRSA or aDSA, so don't worry */
2115	if ((dh_tmp || dh_rsa || dh_dsa) &&
2116		(rsa_enc || rsa_sign || dsa_sign))
2117	mask_k|=SSL_kEDH;
2118	if ((dh_tmp_export || dh_rsa_export || dh_dsa_export) &&
2119		(rsa_enc || rsa_sign || dsa_sign))
2120	emask_k|=SSL_kEDH;
2121#endif
2122
2123	if (dh_tmp_export)
2124		emask_k|=SSL_kEDH;
2125
2126	if (dh_tmp)
2127		mask_k|=SSL_kEDH;
2128
2129	if (dh_rsa)
2130		mask_k|=SSL_kDHr;
2131	if (dh_rsa_export)
2132		emask_k|=SSL_kDHr;
2133
2134	if (dh_dsa)
2135		mask_k|=SSL_kDHd;
2136	if (dh_dsa_export)
2137		emask_k|=SSL_kDHd;
2138
2139	if (rsa_enc || rsa_sign) {
2140		mask_a|=SSL_aRSA;
2141		emask_a|=SSL_aRSA;
2142	}
2143
2144	if (dsa_sign) {
2145		mask_a|=SSL_aDSS;
2146		emask_a|=SSL_aDSS;
2147	}
2148
2149	mask_a|=SSL_aNULL;
2150	emask_a|=SSL_aNULL;
2151
2152#ifndef OPENSSL_NO_KRB5
2153	mask_k|=SSL_kKRB5;
2154	mask_a|=SSL_aKRB5;
2155	emask_k|=SSL_kKRB5;
2156	emask_a|=SSL_aKRB5;
2157#endif
2158
2159	/*
2160	 * An ECC certificate may be usable for ECDH and/or
2161	 * ECDSA cipher suites depending on the key usage extension.
2162	 */
2163	if (have_ecc_cert) {
2164		/* This call populates extension flags (ex_flags) */
2165		x = (c->pkeys[SSL_PKEY_ECC]).x509;
2166		X509_check_purpose(x, -1, 0);
2167		ecdh_ok = (x->ex_flags & EXFLAG_KUSAGE) ?
2168		(x->ex_kusage & X509v3_KU_KEY_AGREEMENT) : 1;
2169		ecdsa_ok = (x->ex_flags & EXFLAG_KUSAGE) ?
2170		(x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE) : 1;
2171		ecc_pkey = X509_get_pubkey(x);
2172		ecc_pkey_size = (ecc_pkey != NULL) ?
2173		EVP_PKEY_bits(ecc_pkey) : 0;
2174		EVP_PKEY_free(ecc_pkey);
2175		if ((x->sig_alg) && (x->sig_alg->algorithm)) {
2176			signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
2177			OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid);
2178		}
2179#ifndef OPENSSL_NO_ECDH
2180		if (ecdh_ok) {
2181
2182			if (pk_nid == NID_rsaEncryption || pk_nid == NID_rsa) {
2183				mask_k|=SSL_kECDHr;
2184				mask_a|=SSL_aECDH;
2185				if (ecc_pkey_size <= 163) {
2186					emask_k|=SSL_kECDHr;
2187					emask_a|=SSL_aECDH;
2188				}
2189			}
2190
2191			if (pk_nid == NID_X9_62_id_ecPublicKey) {
2192				mask_k|=SSL_kECDHe;
2193				mask_a|=SSL_aECDH;
2194				if (ecc_pkey_size <= 163) {
2195					emask_k|=SSL_kECDHe;
2196					emask_a|=SSL_aECDH;
2197				}
2198			}
2199		}
2200#endif
2201#ifndef OPENSSL_NO_ECDSA
2202		if (ecdsa_ok) {
2203			mask_a|=SSL_aECDSA;
2204			emask_a|=SSL_aECDSA;
2205		}
2206#endif
2207	}
2208
2209#ifndef OPENSSL_NO_ECDH
2210	if (have_ecdh_tmp) {
2211		mask_k|=SSL_kEECDH;
2212		emask_k|=SSL_kEECDH;
2213	}
2214#endif
2215
2216#ifndef OPENSSL_NO_PSK
2217	mask_k |= SSL_kPSK;
2218	mask_a |= SSL_aPSK;
2219	emask_k |= SSL_kPSK;
2220	emask_a |= SSL_aPSK;
2221#endif
2222
2223	c->mask_k = mask_k;
2224	c->mask_a = mask_a;
2225	c->export_mask_k = emask_k;
2226	c->export_mask_a = emask_a;
2227	c->valid = 1;
2228}
2229
2230/* This handy macro borrowed from crypto/x509v3/v3_purp.c */
2231#define ku_reject(x, usage) \
2232	(((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
2233
2234#ifndef OPENSSL_NO_EC
2235
2236int
2237ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
2238{
2239	unsigned long		 alg_k, alg_a;
2240	EVP_PKEY		*pkey = NULL;
2241	int			 keysize = 0;
2242	int			 signature_nid = 0, md_nid = 0, pk_nid = 0;
2243	const SSL_CIPHER	*cs = s->s3->tmp.new_cipher;
2244
2245	alg_k = cs->algorithm_mkey;
2246	alg_a = cs->algorithm_auth;
2247
2248	if (SSL_C_IS_EXPORT(cs)) {
2249		/* ECDH key length in export ciphers must be <= 163 bits */
2250		pkey = X509_get_pubkey(x);
2251		if (pkey == NULL)
2252			return (0);
2253		keysize = EVP_PKEY_bits(pkey);
2254		EVP_PKEY_free(pkey);
2255		if (keysize > 163)
2256			return (0);
2257	}
2258
2259	/* This call populates the ex_flags field correctly */
2260	X509_check_purpose(x, -1, 0);
2261	if ((x->sig_alg) && (x->sig_alg->algorithm)) {
2262		signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
2263		OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid);
2264	}
2265	if (alg_k & SSL_kECDHe || alg_k & SSL_kECDHr) {
2266		/* key usage, if present, must allow key agreement */
2267		if (ku_reject(x, X509v3_KU_KEY_AGREEMENT)) {
2268			SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2269			    SSL_R_ECC_CERT_NOT_FOR_KEY_AGREEMENT);
2270			return (0);
2271		}
2272		if ((alg_k & SSL_kECDHe) && TLS1_get_version(s) <
2273		    TLS1_2_VERSION) {
2274			/* signature alg must be ECDSA */
2275			if (pk_nid != NID_X9_62_id_ecPublicKey) {
2276				SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2277				    SSL_R_ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE);
2278				return (0);
2279			}
2280		}
2281		if ((alg_k & SSL_kECDHr) && TLS1_get_version(s) <
2282		    TLS1_2_VERSION) {
2283			/* signature alg must be RSA */
2284			if (pk_nid != NID_rsaEncryption && pk_nid != NID_rsa) {
2285				SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2286				    SSL_R_ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE);
2287				return (0);
2288			}
2289		}
2290	}
2291	if (alg_a & SSL_aECDSA) {
2292		/* key usage, if present, must allow signing */
2293		if (ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE)) {
2294			SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2295			    SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2296			return (0);
2297		}
2298	}
2299
2300	return (1);
2301	/* all checks are ok */
2302}
2303
2304#endif
2305
2306/* THIS NEEDS CLEANING UP */
2307CERT_PKEY *
2308ssl_get_server_send_pkey(const SSL *s)
2309{
2310	unsigned long	 alg_k, alg_a;
2311	CERT		*c;
2312	int		 i;
2313
2314	c = s->cert;
2315	ssl_set_cert_masks(c, s->s3->tmp.new_cipher);
2316
2317	alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2318	alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2319
2320	if (alg_k & (SSL_kECDHr|SSL_kECDHe)) {
2321		/*
2322		 * We don't need to look at SSL_kEECDH
2323		 * since no certificate is needed for
2324		 * anon ECDH and for authenticated
2325		 * EECDH, the check for the auth
2326		 * algorithm will set i correctly
2327		 * NOTE: For ECDH-RSA, we need an ECC
2328		 * not an RSA cert but for EECDH-RSA
2329		 * we need an RSA cert. Placing the
2330		 * checks for SSL_kECDH before RSA
2331		 * checks ensures the correct cert is chosen.
2332		 */
2333		i = SSL_PKEY_ECC;
2334	} else if (alg_a & SSL_aECDSA) {
2335		i = SSL_PKEY_ECC;
2336	} else if (alg_k & SSL_kDHr)
2337		i = SSL_PKEY_DH_RSA;
2338	else if (alg_k & SSL_kDHd)
2339		i = SSL_PKEY_DH_DSA;
2340	else if (alg_a & SSL_aDSS)
2341		i = SSL_PKEY_DSA_SIGN;
2342	else if (alg_a & SSL_aRSA) {
2343		if (c->pkeys[SSL_PKEY_RSA_ENC].x509 == NULL)
2344			i = SSL_PKEY_RSA_SIGN;
2345		else
2346			i = SSL_PKEY_RSA_ENC;
2347	} else if (alg_a & SSL_aKRB5) {
2348		/* VRS something else here? */
2349		return (NULL);
2350	} else if (alg_a & SSL_aGOST94)
2351		i = SSL_PKEY_GOST94;
2352	else if (alg_a & SSL_aGOST01)
2353		i = SSL_PKEY_GOST01;
2354	else { /* if (alg_a & SSL_aNULL) */
2355		SSLerr(SSL_F_SSL_GET_SERVER_SEND_PKEY,
2356		    ERR_R_INTERNAL_ERROR);
2357		return (NULL);
2358	}
2359
2360	return (c->pkeys + i);
2361}
2362
2363X509 *
2364ssl_get_server_send_cert(const SSL *s)
2365{
2366	CERT_PKEY	*cpk;
2367
2368	cpk = ssl_get_server_send_pkey(s);
2369	if (!cpk)
2370		return (NULL);
2371	return (cpk->x509);
2372}
2373
2374EVP_PKEY *
2375ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher, const EVP_MD **pmd)
2376{
2377	unsigned long	 alg_a;
2378	CERT		*c;
2379	int		 idx = -1;
2380
2381	alg_a = cipher->algorithm_auth;
2382	c = s->cert;
2383
2384	if ((alg_a & SSL_aDSS) &&
2385	    (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
2386		idx = SSL_PKEY_DSA_SIGN;
2387	else if (alg_a & SSL_aRSA) {
2388		if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
2389			idx = SSL_PKEY_RSA_SIGN;
2390		else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
2391			idx = SSL_PKEY_RSA_ENC;
2392	} else if ((alg_a & SSL_aECDSA) &&
2393	    (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2394		idx = SSL_PKEY_ECC;
2395	if (idx == -1) {
2396		SSLerr(SSL_F_SSL_GET_SIGN_PKEY,
2397		    ERR_R_INTERNAL_ERROR);
2398		return (NULL);
2399	}
2400	if (pmd)
2401		*pmd = c->pkeys[idx].digest;
2402	return (c->pkeys[idx].privatekey);
2403}
2404
2405void
2406ssl_update_cache(SSL *s, int mode)
2407{
2408	int	i;
2409
2410	/*
2411	 * If the session_id_length is 0, we are not supposed to cache it,
2412	 * and it would be rather hard to do anyway :-)
2413	 */
2414	if (s->session->session_id_length == 0)
2415		return;
2416
2417	i = s->session_ctx->session_cache_mode;
2418	if ((i & mode) && (!s->hit) && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
2419	    || SSL_CTX_add_session(s->session_ctx, s->session))
2420	    && (s->session_ctx->new_session_cb != NULL)) {
2421		CRYPTO_add(&s->session->references, 1, CRYPTO_LOCK_SSL_SESSION);
2422		if (!s->session_ctx->new_session_cb(s, s->session))
2423			SSL_SESSION_free(s->session);
2424	}
2425
2426	/* auto flush every 255 connections */
2427	if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) &&
2428	    ((i & mode) == mode)) {
2429		if ((((mode & SSL_SESS_CACHE_CLIENT) ?
2430		    s->session_ctx->stats.sess_connect_good :
2431		    s->session_ctx->stats.sess_accept_good) & 0xff) == 0xff) {
2432			SSL_CTX_flush_sessions(s->session_ctx, time(NULL));
2433		}
2434	}
2435}
2436
2437const SSL_METHOD *
2438SSL_get_ssl_method(SSL *s)
2439{
2440	return (s->method);
2441}
2442
2443int
2444SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
2445{
2446	int	conn = -1;
2447	int	ret = 1;
2448
2449	if (s->method != meth) {
2450		if (s->handshake_func != NULL)
2451			conn = (s->handshake_func == s->method->ssl_connect);
2452
2453		if (s->method->version == meth->version)
2454			s->method = meth;
2455		else {
2456			s->method->ssl_free(s);
2457			s->method = meth;
2458			ret = s->method->ssl_new(s);
2459		}
2460
2461		if (conn == 1)
2462			s->handshake_func = meth->ssl_connect;
2463		else if (conn == 0)
2464			s->handshake_func = meth->ssl_accept;
2465	}
2466	return (ret);
2467}
2468
2469int
2470SSL_get_error(const SSL *s, int i)
2471{
2472	int		 reason;
2473	unsigned long	 l;
2474	BIO		*bio;
2475
2476	if (i > 0)
2477		return (SSL_ERROR_NONE);
2478
2479	/* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake
2480	 * etc, where we do encode the error */
2481	if ((l = ERR_peek_error()) != 0) {
2482		if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2483			return (SSL_ERROR_SYSCALL);
2484		else
2485			return (SSL_ERROR_SSL);
2486	}
2487
2488	if ((i < 0) && SSL_want_read(s)) {
2489		bio = SSL_get_rbio(s);
2490		if (BIO_should_read(bio))
2491			return (SSL_ERROR_WANT_READ);
2492		else if (BIO_should_write(bio))
2493			/*
2494			 * This one doesn't make too much sense...  We never
2495			 * try to write to the rbio, and an application
2496			 * program where rbio and wbio are separate couldn't
2497			 * even know what it should wait for.  However if we
2498			 * ever set s->rwstate incorrectly (so that we have
2499			 * SSL_want_read(s) instead of SSL_want_write(s))
2500			 * and rbio and wbio *are* the same, this test works
2501			 * around that bug; so it might be safer to keep it.
2502			 */
2503		return (SSL_ERROR_WANT_WRITE);
2504		else if (BIO_should_io_special(bio)) {
2505			reason = BIO_get_retry_reason(bio);
2506			if (reason == BIO_RR_CONNECT)
2507				return (SSL_ERROR_WANT_CONNECT);
2508			else if (reason == BIO_RR_ACCEPT)
2509				return (SSL_ERROR_WANT_ACCEPT);
2510			else
2511				return (SSL_ERROR_SYSCALL); /* unknown */
2512		}
2513	}
2514
2515	if ((i < 0) && SSL_want_write(s)) {
2516		bio = SSL_get_wbio(s);
2517		if (BIO_should_write(bio))
2518			return (SSL_ERROR_WANT_WRITE);
2519		else if (BIO_should_read(bio)) {
2520			/*
2521			 * See above (SSL_want_read(s) with
2522			 * BIO_should_write(bio))
2523			 */
2524			return (SSL_ERROR_WANT_READ);
2525		} else if (BIO_should_io_special(bio)) {
2526			reason = BIO_get_retry_reason(bio);
2527			if (reason == BIO_RR_CONNECT)
2528				return (SSL_ERROR_WANT_CONNECT);
2529			else if (reason == BIO_RR_ACCEPT)
2530				return (SSL_ERROR_WANT_ACCEPT);
2531			else
2532				return (SSL_ERROR_SYSCALL);
2533		}
2534	}
2535	if ((i < 0) && SSL_want_x509_lookup(s)) {
2536		return (SSL_ERROR_WANT_X509_LOOKUP);
2537	}
2538
2539	if (i == 0) {
2540		if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2541		    (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
2542		return (SSL_ERROR_ZERO_RETURN);
2543	}
2544	return (SSL_ERROR_SYSCALL);
2545}
2546
2547int
2548SSL_do_handshake(SSL *s)
2549{
2550	int	ret = 1;
2551
2552	if (s->handshake_func == NULL) {
2553		SSLerr(SSL_F_SSL_DO_HANDSHAKE,
2554		    SSL_R_CONNECTION_TYPE_NOT_SET);
2555		return (-1);
2556	}
2557
2558	s->method->ssl_renegotiate_check(s);
2559
2560	if (SSL_in_init(s) || SSL_in_before(s)) {
2561		ret = s->handshake_func(s);
2562	}
2563	return (ret);
2564}
2565
2566/*
2567 * For the next 2 functions, SSL_clear() sets shutdown and so
2568 * one of these calls will reset it
2569 */
2570void
2571SSL_set_accept_state(SSL *s)
2572{
2573	s->server = 1;
2574	s->shutdown = 0;
2575	s->state = SSL_ST_ACCEPT|SSL_ST_BEFORE;
2576	s->handshake_func = s->method->ssl_accept;
2577	/* clear the current cipher */
2578	ssl_clear_cipher_ctx(s);
2579	ssl_clear_hash_ctx(&s->read_hash);
2580	ssl_clear_hash_ctx(&s->write_hash);
2581}
2582
2583void
2584SSL_set_connect_state(SSL *s)
2585{
2586	s->server = 0;
2587	s->shutdown = 0;
2588	s->state = SSL_ST_CONNECT|SSL_ST_BEFORE;
2589	s->handshake_func = s->method->ssl_connect;
2590	/* clear the current cipher */
2591	ssl_clear_cipher_ctx(s);
2592	ssl_clear_hash_ctx(&s->read_hash);
2593	ssl_clear_hash_ctx(&s->write_hash);
2594}
2595
2596int
2597ssl_undefined_function(SSL *s)
2598{
2599	SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION,
2600	    ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2601	return (0);
2602}
2603
2604int
2605ssl_undefined_void_function(void)
2606{
2607	SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
2608	    ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2609	return (0);
2610}
2611
2612int
2613ssl_undefined_const_function(const SSL *s)
2614{
2615	SSLerr(SSL_F_SSL_UNDEFINED_CONST_FUNCTION,
2616	    ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2617	return (0);
2618}
2619
2620SSL_METHOD *
2621ssl_bad_method(int ver)
2622{
2623	SSLerr(SSL_F_SSL_BAD_METHOD,
2624	    ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2625	return (NULL);
2626}
2627
2628const char *
2629SSL_get_version(const SSL *s)
2630{
2631	if (s->version == TLS1_2_VERSION)
2632		return ("TLSv1.2");
2633	else if (s->version == TLS1_1_VERSION)
2634		return ("TLSv1.1");
2635	else if (s->version == TLS1_VERSION)
2636		return ("TLSv1");
2637	else if (s->version == SSL3_VERSION)
2638		return ("SSLv3");
2639	else
2640		return ("unknown");
2641}
2642
2643SSL *
2644SSL_dup(SSL *s)
2645{
2646	STACK_OF(X509_NAME) *sk;
2647	X509_NAME *xn;
2648	SSL *ret;
2649	int i;
2650
2651	if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
2652		return (NULL);
2653
2654	ret->version = s->version;
2655	ret->type = s->type;
2656	ret->method = s->method;
2657
2658	if (s->session != NULL) {
2659		/* This copies session-id, SSL_METHOD, sid_ctx, and 'cert' */
2660		SSL_copy_session_id(ret, s);
2661	} else {
2662		/*
2663		 * No session has been established yet, so we have to expect
2664		 * that s->cert or ret->cert will be changed later --
2665		 * they should not both point to the same object,
2666		 * and thus we can't use SSL_copy_session_id.
2667		 */
2668
2669		ret->method->ssl_free(ret);
2670		ret->method = s->method;
2671		ret->method->ssl_new(ret);
2672
2673		if (s->cert != NULL) {
2674			if (ret->cert != NULL) {
2675				ssl_cert_free(ret->cert);
2676			}
2677			ret->cert = ssl_cert_dup(s->cert);
2678			if (ret->cert == NULL)
2679				goto err;
2680		}
2681
2682		SSL_set_session_id_context(ret,
2683		s->sid_ctx, s->sid_ctx_length);
2684	}
2685
2686	ret->options = s->options;
2687	ret->mode = s->mode;
2688	SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
2689	SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
2690	ret->msg_callback = s->msg_callback;
2691	ret->msg_callback_arg = s->msg_callback_arg;
2692	SSL_set_verify(ret, SSL_get_verify_mode(s),
2693	SSL_get_verify_callback(s));
2694	SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
2695	ret->generate_session_id = s->generate_session_id;
2696
2697	SSL_set_info_callback(ret, SSL_get_info_callback(s));
2698
2699	ret->debug = s->debug;
2700
2701	/* copy app data, a little dangerous perhaps */
2702	if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL,
2703	    &ret->ex_data, &s->ex_data))
2704		goto err;
2705
2706	/* setup rbio, and wbio */
2707	if (s->rbio != NULL) {
2708		if (!BIO_dup_state(s->rbio,(char *)&ret->rbio))
2709			goto err;
2710	}
2711	if (s->wbio != NULL) {
2712		if (s->wbio != s->rbio) {
2713			if (!BIO_dup_state(s->wbio,(char *)&ret->wbio))
2714				goto err;
2715		} else
2716			ret->wbio = ret->rbio;
2717	}
2718	ret->rwstate = s->rwstate;
2719	ret->in_handshake = s->in_handshake;
2720	ret->handshake_func = s->handshake_func;
2721	ret->server = s->server;
2722	ret->renegotiate = s->renegotiate;
2723	ret->new_session = s->new_session;
2724	ret->quiet_shutdown = s->quiet_shutdown;
2725	ret->shutdown = s->shutdown;
2726	/* SSL_dup does not really work at any state, though */
2727	ret->state=s->state;
2728	ret->rstate = s->rstate;
2729
2730	/*
2731	 * Would have to copy ret->init_buf, ret->init_msg, ret->init_num,
2732	 * ret->init_off
2733	 */
2734	ret->init_num = 0;
2735
2736	ret->hit = s->hit;
2737
2738	X509_VERIFY_PARAM_inherit(ret->param, s->param);
2739
2740	/* dup the cipher_list and cipher_list_by_id stacks */
2741	if (s->cipher_list != NULL) {
2742		if ((ret->cipher_list =
2743		    sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
2744			goto err;
2745	}
2746	if (s->cipher_list_by_id != NULL) {
2747		if ((ret->cipher_list_by_id =
2748		    sk_SSL_CIPHER_dup(s->cipher_list_by_id)) == NULL)
2749			goto err;
2750	}
2751
2752	/* Dup the client_CA list */
2753	if (s->client_CA != NULL) {
2754		if ((sk = sk_X509_NAME_dup(s->client_CA)) == NULL) goto err;
2755			ret->client_CA = sk;
2756		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2757			xn = sk_X509_NAME_value(sk, i);
2758			if (sk_X509_NAME_set(sk, i,
2759			    X509_NAME_dup(xn)) == NULL) {
2760				X509_NAME_free(xn);
2761				goto err;
2762			}
2763		}
2764	}
2765
2766	if (0) {
2767 err:
2768		if (ret != NULL)
2769			SSL_free(ret);
2770		ret = NULL;
2771	}
2772	return (ret);
2773}
2774
2775void
2776ssl_clear_cipher_ctx(SSL *s)
2777{
2778	if (s->enc_read_ctx != NULL) {
2779		EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
2780		free(s->enc_read_ctx);
2781		s->enc_read_ctx = NULL;
2782	}
2783	if (s->enc_write_ctx != NULL) {
2784		EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
2785		free(s->enc_write_ctx);
2786		s->enc_write_ctx = NULL;
2787	}
2788#ifndef OPENSSL_NO_COMP
2789	if (s->expand != NULL) {
2790		COMP_CTX_free(s->expand);
2791		s->expand = NULL;
2792	}
2793	if (s->compress != NULL) {
2794		COMP_CTX_free(s->compress);
2795		s->compress = NULL;
2796	}
2797#endif
2798}
2799
2800/* Fix this function so that it takes an optional type parameter */
2801X509 *
2802SSL_get_certificate(const SSL *s)
2803{
2804	if (s->cert != NULL)
2805		return (s->cert->key->x509);
2806	else
2807		return (NULL);
2808}
2809
2810/* Fix this function so that it takes an optional type parameter */
2811EVP_PKEY *
2812SSL_get_privatekey(SSL *s)
2813{
2814	if (s->cert != NULL)
2815		return (s->cert->key->privatekey);
2816	else
2817		return (NULL);
2818}
2819
2820const SSL_CIPHER *
2821SSL_get_current_cipher(const SSL *s)
2822{
2823	if ((s->session != NULL) && (s->session->cipher != NULL))
2824		return (s->session->cipher);
2825	return (NULL);
2826}
2827#ifdef OPENSSL_NO_COMP
2828const void *
2829SSL_get_current_compression(SSL *s)
2830{
2831	return (NULL);
2832}
2833
2834const void *
2835SSL_get_current_expansion(SSL *s)
2836{
2837	return (NULL);
2838}
2839#else
2840
2841const COMP_METHOD *
2842SSL_get_current_compression(SSL *s)
2843{
2844	if (s->compress != NULL)
2845		return (s->compress->meth);
2846	return (NULL);
2847}
2848
2849const COMP_METHOD *
2850SSL_get_current_expansion(SSL *s)
2851{
2852	if (s->expand != NULL)
2853		return (s->expand->meth);
2854	return (NULL);
2855}
2856#endif
2857
2858int
2859ssl_init_wbio_buffer(SSL *s, int push)
2860{
2861	BIO	*bbio;
2862
2863	if (s->bbio == NULL) {
2864		bbio = BIO_new(BIO_f_buffer());
2865		if (bbio == NULL)
2866			return (0);
2867		s->bbio = bbio;
2868	} else {
2869		bbio = s->bbio;
2870		if (s->bbio == s->wbio)
2871			s->wbio = BIO_pop(s->wbio);
2872	}
2873	(void)BIO_reset(bbio);
2874/*	if (!BIO_set_write_buffer_size(bbio,16*1024)) */
2875	if (!BIO_set_read_buffer_size(bbio, 1)) {
2876		SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER,
2877		    ERR_R_BUF_LIB);
2878		return (0);
2879	}
2880	if (push) {
2881		if (s->wbio != bbio)
2882			s->wbio = BIO_push(bbio, s->wbio);
2883	} else {
2884		if (s->wbio == bbio)
2885			s->wbio = BIO_pop(bbio);
2886	}
2887	return (1);
2888}
2889
2890void
2891ssl_free_wbio_buffer(SSL *s)
2892{
2893	if (s->bbio == NULL)
2894		return;
2895
2896	if (s->bbio == s->wbio) {
2897		/* remove buffering */
2898		s->wbio = BIO_pop(s->wbio);
2899	}
2900	BIO_free(s->bbio);
2901	s->bbio = NULL;
2902}
2903
2904void
2905SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
2906{
2907	ctx->quiet_shutdown = mode;
2908}
2909
2910int
2911SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
2912{
2913	return (ctx->quiet_shutdown);
2914}
2915
2916void
2917SSL_set_quiet_shutdown(SSL *s, int mode)
2918{
2919	s->quiet_shutdown = mode;
2920}
2921
2922int
2923SSL_get_quiet_shutdown(const SSL *s)
2924{
2925	return (s->quiet_shutdown);
2926}
2927
2928void
2929SSL_set_shutdown(SSL *s, int mode)
2930{
2931	s->shutdown = mode;
2932}
2933
2934int
2935SSL_get_shutdown(const SSL *s)
2936{
2937	return (s->shutdown);
2938}
2939
2940int
2941SSL_version(const SSL *s)
2942{
2943	return (s->version);
2944}
2945
2946SSL_CTX *
2947SSL_get_SSL_CTX(const SSL *ssl)
2948{
2949	return (ssl->ctx);
2950}
2951
2952SSL_CTX *
2953SSL_set_SSL_CTX(SSL *ssl, SSL_CTX* ctx)
2954{
2955	if (ssl->ctx == ctx)
2956		return (ssl->ctx);
2957#ifndef OPENSSL_NO_TLSEXT
2958	if (ctx == NULL)
2959		ctx = ssl->initial_ctx;
2960#endif
2961	if (ssl->cert != NULL)
2962		ssl_cert_free(ssl->cert);
2963	ssl->cert = ssl_cert_dup(ctx->cert);
2964	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
2965	if (ssl->ctx != NULL)
2966		SSL_CTX_free(ssl->ctx); /* decrement reference count */
2967	ssl->ctx = ctx;
2968	return (ssl->ctx);
2969}
2970
2971#ifndef OPENSSL_NO_STDIO
2972int
2973SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
2974{
2975	return (X509_STORE_set_default_paths(ctx->cert_store));
2976}
2977
2978int
2979SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
2980    const char *CApath)
2981{
2982	return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
2983}
2984#endif
2985
2986void
2987SSL_set_info_callback(SSL *ssl,
2988    void (*cb)(const SSL *ssl, int type, int val))
2989{
2990	ssl->info_callback = cb;
2991}
2992
2993/*
2994 * One compiler (Diab DCC) doesn't like argument names in returned
2995 * function pointer.
2996 */
2997void (*SSL_get_info_callback(const SSL *ssl))(const SSL * /*ssl*/,int /*type*/,int /*val*/)
2998{
2999	return (ssl->info_callback);
3000}
3001
3002int
3003SSL_state(const SSL *ssl)
3004{
3005	return (ssl->state);
3006}
3007
3008void
3009SSL_set_state(SSL *ssl, int state)
3010{
3011	ssl->state = state;
3012}
3013
3014void
3015SSL_set_verify_result(SSL *ssl, long arg)
3016{
3017	ssl->verify_result = arg;
3018}
3019
3020long
3021SSL_get_verify_result(const SSL *ssl)
3022{
3023	return (ssl->verify_result);
3024}
3025
3026int
3027SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
3028    CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
3029{
3030	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp,
3031	    new_func, dup_func, free_func));
3032}
3033
3034int
3035SSL_set_ex_data(SSL *s, int idx, void *arg)
3036{
3037	return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3038}
3039
3040void *
3041SSL_get_ex_data(const SSL *s, int idx)
3042{
3043	return (CRYPTO_get_ex_data(&s->ex_data, idx));
3044}
3045
3046int
3047SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
3048    CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
3049{
3050	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp,
3051	    new_func, dup_func, free_func));
3052}
3053
3054int
3055SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
3056{
3057	return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3058}
3059
3060void *
3061SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
3062{
3063	return (CRYPTO_get_ex_data(&s->ex_data, idx));
3064}
3065
3066int
3067ssl_ok(SSL *s)
3068{
3069	return (1);
3070}
3071
3072X509_STORE *
3073SSL_CTX_get_cert_store(const SSL_CTX *ctx)
3074{
3075	return (ctx->cert_store);
3076}
3077
3078void
3079SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
3080{
3081	if (ctx->cert_store != NULL)
3082		X509_STORE_free(ctx->cert_store);
3083	ctx->cert_store = store;
3084}
3085
3086int
3087SSL_want(const SSL *s)
3088{
3089	return (s->rwstate);
3090}
3091
3092/*!
3093 * \brief Set the callback for generating temporary RSA keys.
3094 * \param ctx the SSL context.
3095 * \param cb the callback
3096 */
3097
3098void
3099SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*cb)(SSL *ssl,
3100    int is_export,
3101int keylength))
3102{
3103	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
3104}
3105
3106void
3107SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb)(SSL *ssl,
3108    int is_export,
3109int keylength))
3110{
3111	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
3112}
3113
3114#ifdef DOXYGEN
3115/*!
3116 * \brief The RSA temporary key callback function.
3117 * \param ssl the SSL session.
3118 * \param is_export \c TRUE if the temp RSA key is for an export ciphersuite.
3119 * \param keylength if \c is_export is \c TRUE, then \c keylength is the size
3120 * of the required key in bits.
3121 * \return the temporary RSA key.
3122 * \sa SSL_CTX_set_tmp_rsa_callback, SSL_set_tmp_rsa_callback
3123 */
3124
3125RSA *
3126cb(SSL *ssl, int is_export, int keylength)
3127{}
3128#endif
3129
3130/*!
3131 * \brief Set the callback for generating temporary DH keys.
3132 * \param ctx the SSL context.
3133 * \param dh the callback
3134 */
3135
3136#ifndef OPENSSL_NO_DH
3137void
3138SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx, DH *(*dh)(SSL *ssl, int is_export,
3139    int keylength))
3140{
3141	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
3142}
3143
3144void
3145SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh)(SSL *ssl, int is_export,
3146    int keylength))
3147{
3148	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
3149}
3150#endif
3151
3152#ifndef OPENSSL_NO_ECDH
3153void
3154SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx, EC_KEY *(*ecdh)(SSL *ssl,
3155    int is_export, int keylength))
3156{
3157	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH_CB,
3158	    (void (*)(void))ecdh);
3159}
3160
3161void
3162SSL_set_tmp_ecdh_callback(SSL *ssl, EC_KEY *(*ecdh)(SSL *ssl, int is_export,
3163    int keylength))
3164{
3165	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH_CB,(void (*)(void))ecdh);
3166}
3167#endif
3168
3169#ifndef OPENSSL_NO_PSK
3170int
3171SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
3172{
3173	if (identity_hint != NULL && strlen(identity_hint) >
3174	    PSK_MAX_IDENTITY_LEN) {
3175		SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT,
3176		    SSL_R_DATA_LENGTH_TOO_LONG);
3177		return (0);
3178	}
3179	if (ctx->psk_identity_hint != NULL)
3180		free(ctx->psk_identity_hint);
3181	if (identity_hint != NULL) {
3182		ctx->psk_identity_hint = BUF_strdup(identity_hint);
3183		if (ctx->psk_identity_hint == NULL)
3184			return (0);
3185	} else
3186		ctx->psk_identity_hint = NULL;
3187	return (1);
3188}
3189
3190int
3191SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
3192{
3193	if (s == NULL)
3194		return (0);
3195
3196	if (s->session == NULL)
3197		return (1); /* session not created yet, ignored */
3198
3199	if (identity_hint != NULL && strlen(identity_hint) >
3200	    PSK_MAX_IDENTITY_LEN) {
3201		SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT,
3202		    SSL_R_DATA_LENGTH_TOO_LONG);
3203		return (0);
3204	}
3205	if (s->session->psk_identity_hint != NULL)
3206		free(s->session->psk_identity_hint);
3207	if (identity_hint != NULL) {
3208		s->session->psk_identity_hint = BUF_strdup(identity_hint);
3209		if (s->session->psk_identity_hint == NULL)
3210			return (0);
3211	} else
3212		s->session->psk_identity_hint = NULL;
3213	return (1);
3214}
3215
3216const char *
3217SSL_get_psk_identity_hint(const SSL *s)
3218{
3219	if (s == NULL || s->session == NULL)
3220		return (NULL);
3221	return (s->session->psk_identity_hint);
3222}
3223
3224const char *
3225SSL_get_psk_identity(const SSL *s)
3226{
3227	if (s == NULL || s->session == NULL)
3228		return (NULL);
3229	return (s->session->psk_identity);
3230}
3231
3232void
3233SSL_set_psk_client_callback(SSL *s,
3234    unsigned int (*cb)(SSL *ssl, const char *hint,
3235    char *identity, unsigned int max_identity_len, unsigned char *psk,
3236    unsigned int max_psk_len))
3237{
3238	s->psk_client_callback = cb;
3239}
3240
3241void
3242SSL_CTX_set_psk_client_callback(SSL_CTX *ctx,
3243    unsigned int (*cb)(SSL *ssl, const char *hint,
3244    char *identity, unsigned int max_identity_len, unsigned char *psk,
3245    unsigned int max_psk_len))
3246{
3247	ctx->psk_client_callback = cb;
3248}
3249
3250void
3251SSL_set_psk_server_callback(SSL *s,
3252    unsigned int (*cb)(SSL *ssl, const char *identity,
3253    unsigned char *psk, unsigned int max_psk_len))
3254{
3255	s->psk_server_callback = cb;
3256}
3257
3258void
3259SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,
3260    unsigned int (*cb)(SSL *ssl, const char *identity,
3261    unsigned char *psk, unsigned int max_psk_len))
3262{
3263	ctx->psk_server_callback = cb;
3264}
3265#endif
3266
3267void
3268SSL_CTX_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version,
3269    int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
3270{
3271	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK,
3272	    (void (*)(void))cb);
3273}
3274
3275void
3276SSL_set_msg_callback(SSL *ssl, void (*cb)(int write_p, int version,
3277    int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
3278{
3279	SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3280}
3281
3282/*
3283 * Allocates new EVP_MD_CTX and sets pointer to it into given pointer
3284 * vairable, freeing  EVP_MD_CTX previously stored in that variable, if
3285 * any. If EVP_MD pointer is passed, initializes ctx with this md
3286 * Returns newly allocated ctx;
3287 */
3288EVP_MD_CTX *
3289ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
3290{
3291	ssl_clear_hash_ctx(hash);
3292	*hash = EVP_MD_CTX_create();
3293	if (md)
3294		EVP_DigestInit_ex(*hash, md, NULL);
3295	return (*hash);
3296}
3297
3298void
3299ssl_clear_hash_ctx(EVP_MD_CTX **hash)
3300{
3301	if (*hash)
3302		EVP_MD_CTX_destroy(*hash);
3303	*hash = NULL;
3304}
3305
3306void
3307SSL_set_debug(SSL *s, int debug)
3308{
3309	s->debug = debug;
3310}
3311
3312int
3313SSL_cache_hit(SSL *s)
3314{
3315	return (s->hit);
3316}
3317
3318IMPLEMENT_STACK_OF(SSL_CIPHER)
3319IMPLEMENT_STACK_OF(SSL_COMP)
3320IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER,
3321    ssl_cipher_id);
3322