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