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