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