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