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