ssl_lib.c revision 1.301
1/* $OpenBSD: ssl_lib.c,v 1.301 2022/08/17 07:39:19 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#include "ssl_tlsext.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->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->ssl_free(s);
212		s->method = s->ctx->method;
213		if (!s->method->ssl_new(s))
214			return (0);
215	} else
216		s->method->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	    ctx->internal->cert);
232	if (ciphers == NULL || sk_SSL_CIPHER_num(ciphers) <= 0) {
233		SSLerrorx(SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
234		return (0);
235	}
236	return (1);
237}
238
239SSL *
240SSL_new(SSL_CTX *ctx)
241{
242	SSL *s;
243	CBS cbs;
244
245	if (ctx == NULL) {
246		SSLerrorx(SSL_R_NULL_SSL_CTX);
247		return (NULL);
248	}
249	if (ctx->method == NULL) {
250		SSLerrorx(SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
251		return (NULL);
252	}
253
254	if ((s = calloc(1, sizeof(*s))) == NULL)
255		goto err;
256	if ((s->internal = calloc(1, sizeof(*s->internal))) == NULL)
257		goto err;
258
259	if ((s->internal->rl = tls12_record_layer_new()) == NULL)
260		goto err;
261
262	s->internal->min_tls_version = ctx->internal->min_tls_version;
263	s->internal->max_tls_version = ctx->internal->max_tls_version;
264	s->internal->min_proto_version = ctx->internal->min_proto_version;
265	s->internal->max_proto_version = ctx->internal->max_proto_version;
266
267	s->internal->options = ctx->internal->options;
268	s->internal->mode = ctx->internal->mode;
269	s->internal->max_cert_list = ctx->internal->max_cert_list;
270	s->internal->num_tickets = ctx->internal->num_tickets;
271
272	if ((s->cert = ssl_cert_dup(ctx->internal->cert)) == NULL)
273		goto err;
274
275	s->internal->read_ahead = ctx->internal->read_ahead;
276	s->internal->msg_callback = ctx->internal->msg_callback;
277	s->internal->msg_callback_arg = ctx->internal->msg_callback_arg;
278	s->verify_mode = ctx->verify_mode;
279	s->sid_ctx_length = ctx->sid_ctx_length;
280	OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx);
281	memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
282	s->internal->verify_callback = ctx->internal->default_verify_callback;
283	s->internal->generate_session_id = ctx->internal->generate_session_id;
284
285	s->param = X509_VERIFY_PARAM_new();
286	if (!s->param)
287		goto err;
288	X509_VERIFY_PARAM_inherit(s->param, ctx->param);
289	s->internal->quiet_shutdown = ctx->internal->quiet_shutdown;
290	s->max_send_fragment = ctx->internal->max_send_fragment;
291
292	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
293	s->ctx = ctx;
294	s->internal->tlsext_debug_cb = 0;
295	s->internal->tlsext_debug_arg = NULL;
296	s->internal->tlsext_ticket_expected = 0;
297	s->tlsext_status_type = -1;
298	s->internal->tlsext_status_expected = 0;
299	s->internal->tlsext_ocsp_ids = NULL;
300	s->internal->tlsext_ocsp_exts = NULL;
301	s->internal->tlsext_ocsp_resp = NULL;
302	s->internal->tlsext_ocsp_resp_len = 0;
303	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
304	s->initial_ctx = ctx;
305
306	if (ctx->internal->tlsext_ecpointformatlist != NULL) {
307		s->internal->tlsext_ecpointformatlist =
308		    calloc(ctx->internal->tlsext_ecpointformatlist_length,
309			sizeof(ctx->internal->tlsext_ecpointformatlist[0]));
310		if (s->internal->tlsext_ecpointformatlist == NULL)
311			goto err;
312		memcpy(s->internal->tlsext_ecpointformatlist,
313		    ctx->internal->tlsext_ecpointformatlist,
314		    ctx->internal->tlsext_ecpointformatlist_length *
315		    sizeof(ctx->internal->tlsext_ecpointformatlist[0]));
316		s->internal->tlsext_ecpointformatlist_length =
317		    ctx->internal->tlsext_ecpointformatlist_length;
318	}
319	if (ctx->internal->tlsext_supportedgroups != NULL) {
320		s->internal->tlsext_supportedgroups =
321		    calloc(ctx->internal->tlsext_supportedgroups_length,
322			sizeof(ctx->internal->tlsext_supportedgroups[0]));
323		if (s->internal->tlsext_supportedgroups == NULL)
324			goto err;
325		memcpy(s->internal->tlsext_supportedgroups,
326		    ctx->internal->tlsext_supportedgroups,
327		    ctx->internal->tlsext_supportedgroups_length *
328		    sizeof(ctx->internal->tlsext_supportedgroups[0]));
329		s->internal->tlsext_supportedgroups_length =
330		    ctx->internal->tlsext_supportedgroups_length;
331	}
332
333	CBS_init(&cbs, ctx->internal->alpn_client_proto_list,
334	    ctx->internal->alpn_client_proto_list_len);
335	if (!CBS_stow(&cbs, &s->internal->alpn_client_proto_list,
336	    &s->internal->alpn_client_proto_list_len))
337		goto err;
338
339	s->verify_result = X509_V_OK;
340
341	s->method = ctx->method;
342
343	if (!s->method->ssl_new(s))
344		goto err;
345
346	s->references = 1;
347	s->server = ctx->method->server;
348
349	SSL_clear(s);
350
351	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->internal->ex_data);
352
353	return (s);
354
355 err:
356	SSL_free(s);
357	SSLerrorx(ERR_R_MALLOC_FAILURE);
358	return (NULL);
359}
360
361int
362SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
363    unsigned int sid_ctx_len)
364{
365	if (sid_ctx_len > sizeof ctx->sid_ctx) {
366		SSLerrorx(SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
367		return (0);
368	}
369	ctx->sid_ctx_length = sid_ctx_len;
370	memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
371
372	return (1);
373}
374
375int
376SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
377    unsigned int sid_ctx_len)
378{
379	if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
380		SSLerror(ssl, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
381		return (0);
382	}
383	ssl->sid_ctx_length = sid_ctx_len;
384	memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
385
386	return (1);
387}
388
389int
390SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
391{
392	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
393	ctx->internal->generate_session_id = cb;
394	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
395	return (1);
396}
397
398int
399SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
400{
401	CRYPTO_w_lock(CRYPTO_LOCK_SSL);
402	ssl->internal->generate_session_id = cb;
403	CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
404	return (1);
405}
406
407int
408SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
409    unsigned int id_len)
410{
411	/*
412	 * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp
413	 * shows how we can "construct" a session to give us the desired
414	 * check - ie. to find if there's a session in the hash table
415	 * that would conflict with any new session built out of this
416	 * id/id_len and the ssl_version in use by this SSL.
417	 */
418	SSL_SESSION r, *p;
419
420	if (id_len > sizeof r.session_id)
421		return (0);
422
423	r.ssl_version = ssl->version;
424	r.session_id_length = id_len;
425	memcpy(r.session_id, id, id_len);
426
427	CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
428	p = lh_SSL_SESSION_retrieve(ssl->ctx->internal->sessions, &r);
429	CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
430	return (p != NULL);
431}
432
433int
434SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
435{
436	return (X509_VERIFY_PARAM_set_purpose(s->param, purpose));
437}
438
439int
440SSL_set_purpose(SSL *s, int purpose)
441{
442	return (X509_VERIFY_PARAM_set_purpose(s->param, purpose));
443}
444
445int
446SSL_CTX_set_trust(SSL_CTX *s, int trust)
447{
448	return (X509_VERIFY_PARAM_set_trust(s->param, trust));
449}
450
451int
452SSL_set_trust(SSL *s, int trust)
453{
454	return (X509_VERIFY_PARAM_set_trust(s->param, trust));
455}
456
457int
458SSL_set1_host(SSL *s, const char *hostname)
459{
460	struct in_addr ina;
461	struct in6_addr in6a;
462
463	if (hostname != NULL && *hostname != '\0' &&
464	    (inet_pton(AF_INET, hostname, &ina) == 1 ||
465	    inet_pton(AF_INET6, hostname, &in6a) == 1))
466		return X509_VERIFY_PARAM_set1_ip_asc(s->param, hostname);
467	else
468		return X509_VERIFY_PARAM_set1_host(s->param, hostname, 0);
469}
470
471void
472SSL_set_hostflags(SSL *s, unsigned int flags)
473{
474	X509_VERIFY_PARAM_set_hostflags(s->param, flags);
475}
476
477const char *
478SSL_get0_peername(SSL *s)
479{
480	return X509_VERIFY_PARAM_get0_peername(s->param);
481}
482
483X509_VERIFY_PARAM *
484SSL_CTX_get0_param(SSL_CTX *ctx)
485{
486	return (ctx->param);
487}
488
489int
490SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
491{
492	return (X509_VERIFY_PARAM_set1(ctx->param, vpm));
493}
494
495X509_VERIFY_PARAM *
496SSL_get0_param(SSL *ssl)
497{
498	return (ssl->param);
499}
500
501int
502SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
503{
504	return (X509_VERIFY_PARAM_set1(ssl->param, vpm));
505}
506
507void
508SSL_free(SSL *s)
509{
510	int	i;
511
512	if (s == NULL)
513		return;
514
515	i = CRYPTO_add(&s->references, -1, CRYPTO_LOCK_SSL);
516	if (i > 0)
517		return;
518
519	X509_VERIFY_PARAM_free(s->param);
520
521	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->internal->ex_data);
522
523	if (s->bbio != NULL) {
524		/* If the buffering BIO is in place, pop it off */
525		if (s->bbio == s->wbio) {
526			s->wbio = BIO_pop(s->wbio);
527		}
528		BIO_free(s->bbio);
529		s->bbio = NULL;
530	}
531
532	if (s->rbio != s->wbio)
533		BIO_free_all(s->rbio);
534	BIO_free_all(s->wbio);
535
536	tls13_ctx_free(s->internal->tls13);
537
538	ssl3_release_init_buffer(s);
539
540	sk_SSL_CIPHER_free(s->cipher_list);
541	sk_SSL_CIPHER_free(s->internal->cipher_list_tls13);
542
543	/* Make the next call work :-) */
544	if (s->session != NULL) {
545		ssl_clear_bad_session(s);
546		SSL_SESSION_free(s->session);
547	}
548
549	ssl_clear_cipher_state(s);
550
551	ssl_cert_free(s->cert);
552
553	free(s->tlsext_hostname);
554	SSL_CTX_free(s->initial_ctx);
555
556	free(s->internal->tlsext_ecpointformatlist);
557	free(s->internal->tlsext_supportedgroups);
558
559	sk_X509_EXTENSION_pop_free(s->internal->tlsext_ocsp_exts,
560	    X509_EXTENSION_free);
561	sk_OCSP_RESPID_pop_free(s->internal->tlsext_ocsp_ids, OCSP_RESPID_free);
562	free(s->internal->tlsext_ocsp_resp);
563
564	sk_X509_NAME_pop_free(s->internal->client_CA, X509_NAME_free);
565
566	if (s->method != NULL)
567		s->method->ssl_free(s);
568
569	SSL_CTX_free(s->ctx);
570
571	free(s->internal->alpn_client_proto_list);
572
573	free(s->internal->quic_transport_params);
574
575#ifndef OPENSSL_NO_SRTP
576	sk_SRTP_PROTECTION_PROFILE_free(s->internal->srtp_profiles);
577#endif
578
579	tls12_record_layer_free(s->internal->rl);
580
581	free(s->internal);
582	free(s);
583}
584
585int
586SSL_up_ref(SSL *s)
587{
588	int refs = CRYPTO_add(&s->references, 1, CRYPTO_LOCK_SSL);
589	return (refs > 1) ? 1 : 0;
590}
591
592void
593SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
594{
595	/* If the output buffering BIO is still in place, remove it */
596	if (s->bbio != NULL) {
597		if (s->wbio == s->bbio) {
598			s->wbio = BIO_next(s->wbio);
599			BIO_set_next(s->bbio, NULL);
600		}
601	}
602
603	if (s->rbio != rbio && s->rbio != s->wbio)
604		BIO_free_all(s->rbio);
605	if (s->wbio != wbio)
606		BIO_free_all(s->wbio);
607	s->rbio = rbio;
608	s->wbio = wbio;
609}
610
611BIO *
612SSL_get_rbio(const SSL *s)
613{
614	return (s->rbio);
615}
616
617void
618SSL_set0_rbio(SSL *s, BIO *rbio)
619{
620	BIO_free_all(s->rbio);
621	s->rbio = rbio;
622}
623
624BIO *
625SSL_get_wbio(const SSL *s)
626{
627	return (s->wbio);
628}
629
630int
631SSL_get_fd(const SSL *s)
632{
633	return (SSL_get_rfd(s));
634}
635
636int
637SSL_get_rfd(const SSL *s)
638{
639	int	 ret = -1;
640	BIO	*b, *r;
641
642	b = SSL_get_rbio(s);
643	r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
644	if (r != NULL)
645		BIO_get_fd(r, &ret);
646	return (ret);
647}
648
649int
650SSL_get_wfd(const SSL *s)
651{
652	int	 ret = -1;
653	BIO	*b, *r;
654
655	b = SSL_get_wbio(s);
656	r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
657	if (r != NULL)
658		BIO_get_fd(r, &ret);
659	return (ret);
660}
661
662int
663SSL_set_fd(SSL *s, int fd)
664{
665	int	 ret = 0;
666	BIO	*bio = NULL;
667
668	bio = BIO_new(BIO_s_socket());
669
670	if (bio == NULL) {
671		SSLerror(s, ERR_R_BUF_LIB);
672		goto err;
673	}
674	BIO_set_fd(bio, fd, BIO_NOCLOSE);
675	SSL_set_bio(s, bio, bio);
676	ret = 1;
677 err:
678	return (ret);
679}
680
681int
682SSL_set_wfd(SSL *s, int fd)
683{
684	int	 ret = 0;
685	BIO	*bio = NULL;
686
687	if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET)
688	    || ((int)BIO_get_fd(s->rbio, NULL) != fd)) {
689		bio = BIO_new(BIO_s_socket());
690
691		if (bio == NULL) {
692			SSLerror(s, ERR_R_BUF_LIB);
693			goto err;
694		}
695		BIO_set_fd(bio, fd, BIO_NOCLOSE);
696		SSL_set_bio(s, SSL_get_rbio(s), bio);
697	} else
698		SSL_set_bio(s, SSL_get_rbio(s), SSL_get_rbio(s));
699	ret = 1;
700 err:
701	return (ret);
702}
703
704int
705SSL_set_rfd(SSL *s, int fd)
706{
707	int	 ret = 0;
708	BIO	*bio = NULL;
709
710	if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET)
711	    || ((int)BIO_get_fd(s->wbio, NULL) != fd)) {
712		bio = BIO_new(BIO_s_socket());
713
714		if (bio == NULL) {
715			SSLerror(s, ERR_R_BUF_LIB);
716			goto err;
717		}
718		BIO_set_fd(bio, fd, BIO_NOCLOSE);
719		SSL_set_bio(s, bio, SSL_get_wbio(s));
720	} else
721		SSL_set_bio(s, SSL_get_wbio(s), SSL_get_wbio(s));
722	ret = 1;
723 err:
724	return (ret);
725}
726
727
728/* return length of latest Finished message we sent, copy to 'buf' */
729size_t
730SSL_get_finished(const SSL *s, void *buf, size_t count)
731{
732	size_t	ret;
733
734	ret = s->s3->hs.finished_len;
735	if (count > ret)
736		count = ret;
737	memcpy(buf, s->s3->hs.finished, count);
738	return (ret);
739}
740
741/* return length of latest Finished message we expected, copy to 'buf' */
742size_t
743SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
744{
745	size_t	ret;
746
747	ret = s->s3->hs.peer_finished_len;
748	if (count > ret)
749		count = ret;
750	memcpy(buf, s->s3->hs.peer_finished, count);
751	return (ret);
752}
753
754
755int
756SSL_get_verify_mode(const SSL *s)
757{
758	return (s->verify_mode);
759}
760
761int
762SSL_get_verify_depth(const SSL *s)
763{
764	return (X509_VERIFY_PARAM_get_depth(s->param));
765}
766
767int
768(*SSL_get_verify_callback(const SSL *s))(int, X509_STORE_CTX *)
769{
770	return (s->internal->verify_callback);
771}
772
773void
774SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb)
775{
776	ctx->internal->keylog_callback = cb;
777}
778
779SSL_CTX_keylog_cb_func
780SSL_CTX_get_keylog_callback(const SSL_CTX *ctx)
781{
782	return (ctx->internal->keylog_callback);
783}
784
785int
786SSL_set_num_tickets(SSL *s, size_t num_tickets)
787{
788	s->internal->num_tickets = num_tickets;
789
790	return 1;
791}
792
793size_t
794SSL_get_num_tickets(const SSL *s)
795{
796	return s->internal->num_tickets;
797}
798
799int
800SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets)
801{
802	ctx->internal->num_tickets = num_tickets;
803
804	return 1;
805}
806
807size_t
808SSL_CTX_get_num_tickets(const SSL_CTX *ctx)
809{
810	return ctx->internal->num_tickets;
811}
812
813int
814SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
815{
816	return (ctx->verify_mode);
817}
818
819int
820SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
821{
822	return (X509_VERIFY_PARAM_get_depth(ctx->param));
823}
824
825int
826(*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))(int, X509_STORE_CTX *)
827{
828	return (ctx->internal->default_verify_callback);
829}
830
831void
832SSL_set_verify(SSL *s, int mode,
833    int (*callback)(int ok, X509_STORE_CTX *ctx))
834{
835	s->verify_mode = mode;
836	if (callback != NULL)
837		s->internal->verify_callback = callback;
838}
839
840void
841SSL_set_verify_depth(SSL *s, int depth)
842{
843	X509_VERIFY_PARAM_set_depth(s->param, depth);
844}
845
846void
847SSL_set_read_ahead(SSL *s, int yes)
848{
849	s->internal->read_ahead = yes;
850}
851
852int
853SSL_get_read_ahead(const SSL *s)
854{
855	return (s->internal->read_ahead);
856}
857
858int
859SSL_pending(const SSL *s)
860{
861	return (s->method->ssl_pending(s));
862}
863
864X509 *
865SSL_get_peer_certificate(const SSL *s)
866{
867	X509 *cert;
868
869	if (s == NULL || s->session == NULL)
870		return NULL;
871
872	if ((cert = s->session->peer_cert) == NULL)
873		return NULL;
874
875	X509_up_ref(cert);
876
877	return cert;
878}
879
880STACK_OF(X509) *
881SSL_get_peer_cert_chain(const SSL *s)
882{
883	if (s == NULL)
884		return NULL;
885
886	/*
887	 * Achtung! Due to API inconsistency, a client includes the peer's leaf
888	 * certificate in the peer certificate chain, while a server does not.
889	 */
890	if (!s->server)
891		return s->s3->hs.peer_certs;
892
893	return s->s3->hs.peer_certs_no_leaf;
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 (s->s3->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	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 (!ssl_security_supported_cipher(s, cipher))
1474			continue;
1475		if (!sk_SSL_CIPHER_push(supported_ciphers, cipher))
1476			goto err;
1477	}
1478
1479	if (sk_SSL_CIPHER_num(supported_ciphers) > 0)
1480		return supported_ciphers;
1481
1482 err:
1483	sk_SSL_CIPHER_free(supported_ciphers);
1484	return NULL;
1485}
1486
1487/* See if we have any ECC cipher suites. */
1488int
1489ssl_has_ecc_ciphers(SSL *s)
1490{
1491	STACK_OF(SSL_CIPHER) *ciphers;
1492	unsigned long alg_k, alg_a;
1493	SSL_CIPHER *cipher;
1494	int i;
1495
1496	if ((ciphers = SSL_get_ciphers(s)) == NULL)
1497		return 0;
1498
1499	for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1500		cipher = sk_SSL_CIPHER_value(ciphers, i);
1501
1502		alg_k = cipher->algorithm_mkey;
1503		alg_a = cipher->algorithm_auth;
1504
1505		if ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))
1506			return 1;
1507	}
1508
1509	return 0;
1510}
1511
1512/* The old interface to get the same thing as SSL_get_ciphers(). */
1513const char *
1514SSL_get_cipher_list(const SSL *s, int n)
1515{
1516	STACK_OF(SSL_CIPHER) *ciphers;
1517	const SSL_CIPHER *cipher;
1518
1519	if ((ciphers = SSL_get_ciphers(s)) == NULL)
1520		return (NULL);
1521	if ((cipher = sk_SSL_CIPHER_value(ciphers, n)) == NULL)
1522		return (NULL);
1523
1524	return (cipher->name);
1525}
1526
1527STACK_OF(SSL_CIPHER) *
1528SSL_CTX_get_ciphers(const SSL_CTX *ctx)
1529{
1530	if (ctx == NULL)
1531		return NULL;
1532	return ctx->cipher_list;
1533}
1534
1535/* Specify the ciphers to be used by default by the SSL_CTX. */
1536int
1537SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
1538{
1539	STACK_OF(SSL_CIPHER) *ciphers;
1540
1541	/*
1542	 * ssl_create_cipher_list may return an empty stack if it was unable to
1543	 * find a cipher matching the given rule string (for example if the
1544	 * rule string specifies a cipher which has been disabled). This is not
1545	 * an error as far as ssl_create_cipher_list is concerned, and hence
1546	 * ctx->cipher_list has been updated.
1547	 */
1548	ciphers = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
1549	    ctx->internal->cipher_list_tls13, str, ctx->internal->cert);
1550	if (ciphers == NULL) {
1551		return (0);
1552	} else if (sk_SSL_CIPHER_num(ciphers) == 0) {
1553		SSLerrorx(SSL_R_NO_CIPHER_MATCH);
1554		return (0);
1555	}
1556	return (1);
1557}
1558
1559int
1560SSL_CTX_set_ciphersuites(SSL_CTX *ctx, const char *str)
1561{
1562	if (!ssl_parse_ciphersuites(&ctx->internal->cipher_list_tls13, str)) {
1563		SSLerrorx(SSL_R_NO_CIPHER_MATCH);
1564		return 0;
1565	}
1566	if (!ssl_merge_cipherlists(ctx->cipher_list,
1567	    ctx->internal->cipher_list_tls13, &ctx->cipher_list))
1568		return 0;
1569
1570	return 1;
1571}
1572
1573/* Specify the ciphers to be used by the SSL. */
1574int
1575SSL_set_cipher_list(SSL *s, const char *str)
1576{
1577	STACK_OF(SSL_CIPHER) *ciphers, *ciphers_tls13;
1578
1579	if ((ciphers_tls13 = s->internal->cipher_list_tls13) == NULL)
1580		ciphers_tls13 = s->ctx->internal->cipher_list_tls13;
1581
1582	/* See comment in SSL_CTX_set_cipher_list. */
1583	ciphers = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
1584	    ciphers_tls13, str, s->cert);
1585	if (ciphers == NULL) {
1586		return (0);
1587	} else if (sk_SSL_CIPHER_num(ciphers) == 0) {
1588		SSLerror(s, SSL_R_NO_CIPHER_MATCH);
1589		return (0);
1590	}
1591	return (1);
1592}
1593
1594int
1595SSL_set_ciphersuites(SSL *s, const char *str)
1596{
1597	STACK_OF(SSL_CIPHER) *ciphers;
1598
1599	if ((ciphers = s->cipher_list) == NULL)
1600		ciphers = s->ctx->cipher_list;
1601
1602	if (!ssl_parse_ciphersuites(&s->internal->cipher_list_tls13, str)) {
1603		SSLerrorx(SSL_R_NO_CIPHER_MATCH);
1604		return (0);
1605	}
1606	if (!ssl_merge_cipherlists(ciphers, s->internal->cipher_list_tls13,
1607	    &s->cipher_list))
1608		return 0;
1609
1610	return 1;
1611}
1612
1613char *
1614SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
1615{
1616	STACK_OF(SSL_CIPHER) *client_ciphers, *server_ciphers;
1617	const SSL_CIPHER *cipher;
1618	size_t curlen = 0;
1619	char *end;
1620	int i;
1621
1622	if (!s->server || s->session == NULL || len < 2)
1623		return NULL;
1624
1625	if ((client_ciphers = s->session->ciphers) == NULL)
1626		return NULL;
1627	if ((server_ciphers = SSL_get_ciphers(s)) == NULL)
1628		return NULL;
1629	if (sk_SSL_CIPHER_num(client_ciphers) == 0 ||
1630	    sk_SSL_CIPHER_num(server_ciphers) == 0)
1631		return NULL;
1632
1633	buf[0] = '\0';
1634	for (i = 0; i < sk_SSL_CIPHER_num(client_ciphers); i++) {
1635		cipher = sk_SSL_CIPHER_value(client_ciphers, i);
1636
1637		if (sk_SSL_CIPHER_find(server_ciphers, cipher) < 0)
1638			continue;
1639
1640		end = buf + curlen;
1641		if (strlcat(buf, cipher->name, len) >= len ||
1642		    (curlen = strlcat(buf, ":", len)) >= len) {
1643			/* remove truncated cipher from list */
1644			*end = '\0';
1645			break;
1646		}
1647	}
1648	/* remove trailing colon */
1649	if ((end = strrchr(buf, ':')) != NULL)
1650		*end = '\0';
1651	return buf;
1652}
1653
1654/*
1655 * Return a servername extension value if provided in Client Hello, or NULL.
1656 * So far, only host_name types are defined (RFC 3546).
1657 */
1658const char *
1659SSL_get_servername(const SSL *s, const int type)
1660{
1661	if (type != TLSEXT_NAMETYPE_host_name)
1662		return (NULL);
1663
1664	return (s->session && !s->tlsext_hostname ?
1665	    s->session->tlsext_hostname :
1666	    s->tlsext_hostname);
1667}
1668
1669int
1670SSL_get_servername_type(const SSL *s)
1671{
1672	if (s->session &&
1673	    (!s->tlsext_hostname ?
1674	    s->session->tlsext_hostname : s->tlsext_hostname))
1675		return (TLSEXT_NAMETYPE_host_name);
1676	return (-1);
1677}
1678
1679/*
1680 * SSL_select_next_proto implements standard protocol selection. It is
1681 * expected that this function is called from the callback set by
1682 * SSL_CTX_set_alpn_select_cb.
1683 *
1684 * The protocol data is assumed to be a vector of 8-bit, length prefixed byte
1685 * strings. The length byte itself is not included in the length. A byte
1686 * string of length 0 is invalid. No byte string may be truncated.
1687 *
1688 * It returns either:
1689 * OPENSSL_NPN_NEGOTIATED if a common protocol was found, or
1690 * OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
1691 */
1692int
1693SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
1694    const unsigned char *server, unsigned int server_len,
1695    const unsigned char *client, unsigned int client_len)
1696{
1697	unsigned int		 i, j;
1698	const unsigned char	*result;
1699	int			 status = OPENSSL_NPN_UNSUPPORTED;
1700
1701	/*
1702	 * For each protocol in server preference order,
1703	 * see if we support it.
1704	 */
1705	for (i = 0; i < server_len; ) {
1706		for (j = 0; j < client_len; ) {
1707			if (server[i] == client[j] &&
1708			    memcmp(&server[i + 1],
1709			    &client[j + 1], server[i]) == 0) {
1710				/* We found a match */
1711				result = &server[i];
1712				status = OPENSSL_NPN_NEGOTIATED;
1713				goto found;
1714			}
1715			j += client[j];
1716			j++;
1717		}
1718		i += server[i];
1719		i++;
1720	}
1721
1722	/* There's no overlap between our protocols and the server's list. */
1723	result = client;
1724	status = OPENSSL_NPN_NO_OVERLAP;
1725
1726 found:
1727	*out = (unsigned char *) result + 1;
1728	*outlen = result[0];
1729	return (status);
1730}
1731
1732/* SSL_get0_next_proto_negotiated is deprecated. */
1733void
1734SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
1735    unsigned int *len)
1736{
1737	*data = NULL;
1738	*len = 0;
1739}
1740
1741/* SSL_CTX_set_next_protos_advertised_cb is deprecated. */
1742void
1743SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx, int (*cb) (SSL *ssl,
1744    const unsigned char **out, unsigned int *outlen, void *arg), void *arg)
1745{
1746}
1747
1748/* SSL_CTX_set_next_proto_select_cb is deprecated. */
1749void
1750SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, int (*cb) (SSL *s,
1751    unsigned char **out, unsigned char *outlen, const unsigned char *in,
1752    unsigned int inlen, void *arg), void *arg)
1753{
1754}
1755
1756/*
1757 * SSL_CTX_set_alpn_protos sets the ALPN protocol list to the specified
1758 * protocols, which must be in wire-format (i.e. a series of non-empty,
1759 * 8-bit length-prefixed strings). Returns 0 on success.
1760 */
1761int
1762SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
1763    unsigned int protos_len)
1764{
1765	CBS cbs;
1766	int failed = 1;
1767
1768	if (protos == NULL)
1769		protos_len = 0;
1770
1771	CBS_init(&cbs, protos, protos_len);
1772
1773	if (protos_len > 0) {
1774		if (!tlsext_alpn_check_format(&cbs))
1775			goto err;
1776	}
1777
1778	if (!CBS_stow(&cbs, &ctx->internal->alpn_client_proto_list,
1779	    &ctx->internal->alpn_client_proto_list_len))
1780		goto err;
1781
1782	failed = 0;
1783
1784 err:
1785	/* NOTE: Return values are the reverse of what you expect. */
1786	return failed;
1787}
1788
1789/*
1790 * SSL_set_alpn_protos sets the ALPN protocol list to the specified
1791 * protocols, which must be in wire-format (i.e. a series of non-empty,
1792 * 8-bit length-prefixed strings). Returns 0 on success.
1793 */
1794int
1795SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
1796    unsigned int protos_len)
1797{
1798	CBS cbs;
1799	int failed = 1;
1800
1801	if (protos == NULL)
1802		protos_len = 0;
1803
1804	CBS_init(&cbs, protos, protos_len);
1805
1806	if (protos_len > 0) {
1807		if (!tlsext_alpn_check_format(&cbs))
1808			goto err;
1809	}
1810
1811	if (!CBS_stow(&cbs, &ssl->internal->alpn_client_proto_list,
1812	    &ssl->internal->alpn_client_proto_list_len))
1813		goto err;
1814
1815	failed = 0;
1816
1817 err:
1818	/* NOTE: Return values are the reverse of what you expect. */
1819	return failed;
1820}
1821
1822/*
1823 * SSL_CTX_set_alpn_select_cb sets a callback function that is called during
1824 * ClientHello processing in order to select an ALPN protocol from the
1825 * client's list of offered protocols.
1826 */
1827void
1828SSL_CTX_set_alpn_select_cb(SSL_CTX* ctx,
1829    int (*cb) (SSL *ssl, const unsigned char **out, unsigned char *outlen,
1830    const unsigned char *in, unsigned int inlen, void *arg), void *arg)
1831{
1832	ctx->internal->alpn_select_cb = cb;
1833	ctx->internal->alpn_select_cb_arg = arg;
1834}
1835
1836/*
1837 * SSL_get0_alpn_selected gets the selected ALPN protocol (if any). On return
1838 * it sets data to point to len bytes of protocol name (not including the
1839 * leading length-prefix byte). If the server didn't respond with* a negotiated
1840 * protocol then len will be zero.
1841 */
1842void
1843SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
1844    unsigned int *len)
1845{
1846	*data = ssl->s3->alpn_selected;
1847	*len = ssl->s3->alpn_selected_len;
1848}
1849
1850void
1851SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb)
1852{
1853	return;
1854}
1855
1856int
1857SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1858    const char *label, size_t llen, const unsigned char *p, size_t plen,
1859    int use_context)
1860{
1861	if (s->internal->tls13 != NULL && s->version == TLS1_3_VERSION) {
1862		if (!use_context) {
1863			p = NULL;
1864			plen = 0;
1865		}
1866		return tls13_exporter(s->internal->tls13, label, llen, p, plen,
1867		    out, olen);
1868	}
1869
1870	return (tls1_export_keying_material(s, out, olen, label, llen, p, plen,
1871	    use_context));
1872}
1873
1874static unsigned long
1875ssl_session_hash(const SSL_SESSION *a)
1876{
1877	unsigned long	l;
1878
1879	l = (unsigned long)
1880	    ((unsigned int) a->session_id[0]     )|
1881	    ((unsigned int) a->session_id[1]<< 8L)|
1882	    ((unsigned long)a->session_id[2]<<16L)|
1883	    ((unsigned long)a->session_id[3]<<24L);
1884	return (l);
1885}
1886
1887/*
1888 * NB: If this function (or indeed the hash function which uses a sort of
1889 * coarser function than this one) is changed, ensure
1890 * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on being
1891 * able to construct an SSL_SESSION that will collide with any existing session
1892 * with a matching session ID.
1893 */
1894static int
1895ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
1896{
1897	if (a->ssl_version != b->ssl_version)
1898		return (1);
1899	if (a->session_id_length != b->session_id_length)
1900		return (1);
1901	if (timingsafe_memcmp(a->session_id, b->session_id, a->session_id_length) != 0)
1902		return (1);
1903	return (0);
1904}
1905
1906/*
1907 * These wrapper functions should remain rather than redeclaring
1908 * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
1909 * variable. The reason is that the functions aren't static, they're exposed via
1910 * ssl.h.
1911 */
1912static unsigned long
1913ssl_session_LHASH_HASH(const void *arg)
1914{
1915	const SSL_SESSION *a = arg;
1916
1917	return ssl_session_hash(a);
1918}
1919
1920static int
1921ssl_session_LHASH_COMP(const void *arg1, const void *arg2)
1922{
1923	const SSL_SESSION *a = arg1;
1924	const SSL_SESSION *b = arg2;
1925
1926	return ssl_session_cmp(a, b);
1927}
1928
1929SSL_CTX *
1930SSL_CTX_new(const SSL_METHOD *meth)
1931{
1932	SSL_CTX	*ret;
1933
1934	if (!OPENSSL_init_ssl(0, NULL)) {
1935		SSLerrorx(SSL_R_LIBRARY_BUG);
1936		return (NULL);
1937	}
1938
1939	if (meth == NULL) {
1940		SSLerrorx(SSL_R_NULL_SSL_METHOD_PASSED);
1941		return (NULL);
1942	}
1943
1944	if ((ret = calloc(1, sizeof(*ret))) == NULL) {
1945		SSLerrorx(ERR_R_MALLOC_FAILURE);
1946		return (NULL);
1947	}
1948	if ((ret->internal = calloc(1, sizeof(*ret->internal))) == NULL) {
1949		free(ret);
1950		SSLerrorx(ERR_R_MALLOC_FAILURE);
1951		return (NULL);
1952	}
1953
1954	if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
1955		SSLerrorx(SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
1956		goto err;
1957	}
1958
1959	ret->method = meth;
1960	ret->internal->min_tls_version = meth->min_tls_version;
1961	ret->internal->max_tls_version = meth->max_tls_version;
1962	ret->internal->min_proto_version = 0;
1963	ret->internal->max_proto_version = 0;
1964	ret->internal->mode = SSL_MODE_AUTO_RETRY;
1965
1966	ret->cert_store = NULL;
1967	ret->internal->session_cache_mode = SSL_SESS_CACHE_SERVER;
1968	ret->internal->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
1969	ret->internal->session_cache_head = NULL;
1970	ret->internal->session_cache_tail = NULL;
1971
1972	/* We take the system default */
1973	ret->session_timeout = ssl_get_default_timeout();
1974
1975	ret->internal->new_session_cb = 0;
1976	ret->internal->remove_session_cb = 0;
1977	ret->internal->get_session_cb = 0;
1978	ret->internal->generate_session_id = 0;
1979
1980	memset((char *)&ret->internal->stats, 0, sizeof(ret->internal->stats));
1981
1982	ret->references = 1;
1983	ret->internal->quiet_shutdown = 0;
1984
1985	ret->internal->info_callback = NULL;
1986
1987	ret->internal->app_verify_callback = 0;
1988	ret->internal->app_verify_arg = NULL;
1989
1990	ret->internal->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
1991	ret->internal->read_ahead = 0;
1992	ret->internal->msg_callback = 0;
1993	ret->internal->msg_callback_arg = NULL;
1994	ret->verify_mode = SSL_VERIFY_NONE;
1995	ret->sid_ctx_length = 0;
1996	ret->internal->default_verify_callback = NULL;
1997
1998	if ((ret->internal->cert = ssl_cert_new()) == NULL)
1999		goto err;
2000
2001	ret->default_passwd_callback = 0;
2002	ret->default_passwd_callback_userdata = NULL;
2003	ret->internal->client_cert_cb = 0;
2004	ret->internal->app_gen_cookie_cb = 0;
2005	ret->internal->app_verify_cookie_cb = 0;
2006
2007	ret->internal->sessions = lh_SSL_SESSION_new();
2008	if (ret->internal->sessions == NULL)
2009		goto err;
2010	ret->cert_store = X509_STORE_new();
2011	if (ret->cert_store == NULL)
2012		goto err;
2013
2014	ssl_create_cipher_list(ret->method, &ret->cipher_list,
2015	    NULL, SSL_DEFAULT_CIPHER_LIST, ret->internal->cert);
2016	if (ret->cipher_list == NULL ||
2017	    sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
2018		SSLerrorx(SSL_R_LIBRARY_HAS_NO_CIPHERS);
2019		goto err2;
2020	}
2021
2022	ret->param = X509_VERIFY_PARAM_new();
2023	if (!ret->param)
2024		goto err;
2025
2026	if ((ret->internal->client_CA = sk_X509_NAME_new_null()) == NULL)
2027		goto err;
2028
2029	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->internal->ex_data);
2030
2031	ret->extra_certs = NULL;
2032
2033	ret->internal->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2034
2035	ret->internal->tlsext_servername_callback = 0;
2036	ret->internal->tlsext_servername_arg = NULL;
2037
2038	/* Setup RFC4507 ticket keys */
2039	arc4random_buf(ret->internal->tlsext_tick_key_name, 16);
2040	arc4random_buf(ret->internal->tlsext_tick_hmac_key, 16);
2041	arc4random_buf(ret->internal->tlsext_tick_aes_key, 16);
2042
2043	ret->internal->tlsext_status_cb = 0;
2044	ret->internal->tlsext_status_arg = NULL;
2045
2046#ifndef OPENSSL_NO_ENGINE
2047	ret->internal->client_cert_engine = NULL;
2048#ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
2049#define eng_strx(x)	#x
2050#define eng_str(x)	eng_strx(x)
2051	/* Use specific client engine automatically... ignore errors */
2052	{
2053		ENGINE *eng;
2054		eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2055		if (!eng) {
2056			ERR_clear_error();
2057			ENGINE_load_builtin_engines();
2058			eng = ENGINE_by_id(eng_str(
2059			    OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2060		}
2061		if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
2062			ERR_clear_error();
2063	}
2064#endif
2065#endif
2066	/*
2067	 * Default is to connect to non-RI servers. When RI is more widely
2068	 * deployed might change this.
2069	 */
2070	ret->internal->options |= SSL_OP_LEGACY_SERVER_CONNECT;
2071
2072	return (ret);
2073 err:
2074	SSLerrorx(ERR_R_MALLOC_FAILURE);
2075 err2:
2076	SSL_CTX_free(ret);
2077	return (NULL);
2078}
2079
2080void
2081SSL_CTX_free(SSL_CTX *ctx)
2082{
2083	int	i;
2084
2085	if (ctx == NULL)
2086		return;
2087
2088	i = CRYPTO_add(&ctx->references, -1, CRYPTO_LOCK_SSL_CTX);
2089	if (i > 0)
2090		return;
2091
2092	X509_VERIFY_PARAM_free(ctx->param);
2093
2094	/*
2095	 * Free internal session cache. However: the remove_cb() may reference
2096	 * the ex_data of SSL_CTX, thus the ex_data store can only be removed
2097	 * after the sessions were flushed.
2098	 * As the ex_data handling routines might also touch the session cache,
2099	 * the most secure solution seems to be: empty (flush) the cache, then
2100	 * free ex_data, then finally free the cache.
2101	 * (See ticket [openssl.org #212].)
2102	 */
2103	if (ctx->internal->sessions != NULL)
2104		SSL_CTX_flush_sessions(ctx, 0);
2105
2106	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ctx, &ctx->internal->ex_data);
2107
2108	lh_SSL_SESSION_free(ctx->internal->sessions);
2109
2110	X509_STORE_free(ctx->cert_store);
2111	sk_SSL_CIPHER_free(ctx->cipher_list);
2112	sk_SSL_CIPHER_free(ctx->internal->cipher_list_tls13);
2113	ssl_cert_free(ctx->internal->cert);
2114	sk_X509_NAME_pop_free(ctx->internal->client_CA, X509_NAME_free);
2115	sk_X509_pop_free(ctx->extra_certs, X509_free);
2116
2117#ifndef OPENSSL_NO_SRTP
2118	if (ctx->internal->srtp_profiles)
2119		sk_SRTP_PROTECTION_PROFILE_free(ctx->internal->srtp_profiles);
2120#endif
2121
2122#ifndef OPENSSL_NO_ENGINE
2123	ENGINE_finish(ctx->internal->client_cert_engine);
2124#endif
2125
2126	free(ctx->internal->tlsext_ecpointformatlist);
2127	free(ctx->internal->tlsext_supportedgroups);
2128
2129	free(ctx->internal->alpn_client_proto_list);
2130
2131	free(ctx->internal);
2132	free(ctx);
2133}
2134
2135int
2136SSL_CTX_up_ref(SSL_CTX *ctx)
2137{
2138	int refs = CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
2139	return ((refs > 1) ? 1 : 0);
2140}
2141
2142pem_password_cb *
2143SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
2144{
2145	return (ctx->default_passwd_callback);
2146}
2147
2148void
2149SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2150{
2151	ctx->default_passwd_callback = cb;
2152}
2153
2154void *
2155SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
2156{
2157	return ctx->default_passwd_callback_userdata;
2158}
2159
2160void
2161SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2162{
2163	ctx->default_passwd_callback_userdata = u;
2164}
2165
2166void
2167SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
2168    int (*cb)(X509_STORE_CTX *, void *), void *arg)
2169{
2170	ctx->internal->app_verify_callback = cb;
2171	ctx->internal->app_verify_arg = arg;
2172}
2173
2174void
2175SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*cb)(int, X509_STORE_CTX *))
2176{
2177	ctx->verify_mode = mode;
2178	ctx->internal->default_verify_callback = cb;
2179}
2180
2181void
2182SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
2183{
2184	X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2185}
2186
2187void
2188ssl_set_cert_masks(SSL_CERT *c, const SSL_CIPHER *cipher)
2189{
2190	unsigned long mask_a, mask_k;
2191	SSL_CERT_PKEY *cpk;
2192
2193	if (c == NULL)
2194		return;
2195
2196	mask_a = SSL_aNULL | SSL_aTLS1_3;
2197	mask_k = SSL_kECDHE | SSL_kTLS1_3;
2198
2199	if (c->dhe_params != NULL || c->dhe_params_cb != NULL ||
2200	    c->dhe_params_auto != 0)
2201		mask_k |= SSL_kDHE;
2202
2203	cpk = &(c->pkeys[SSL_PKEY_ECC]);
2204	if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2205		/* Key usage, if present, must allow signing. */
2206		if (X509_get_key_usage(cpk->x509) & X509v3_KU_DIGITAL_SIGNATURE)
2207			mask_a |= SSL_aECDSA;
2208	}
2209
2210	cpk = &(c->pkeys[SSL_PKEY_GOST01]);
2211	if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2212		mask_k |= SSL_kGOST;
2213		mask_a |= SSL_aGOST01;
2214	}
2215
2216	cpk = &(c->pkeys[SSL_PKEY_RSA]);
2217	if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2218		mask_a |= SSL_aRSA;
2219		mask_k |= SSL_kRSA;
2220	}
2221
2222	c->mask_k = mask_k;
2223	c->mask_a = mask_a;
2224	c->valid = 1;
2225}
2226
2227/* See if this handshake is using an ECC cipher suite. */
2228int
2229ssl_using_ecc_cipher(SSL *s)
2230{
2231	unsigned long alg_a, alg_k;
2232
2233	alg_a = s->s3->hs.cipher->algorithm_auth;
2234	alg_k = s->s3->hs.cipher->algorithm_mkey;
2235
2236	return s->session->tlsext_ecpointformatlist != NULL &&
2237	    s->session->tlsext_ecpointformatlist_length > 0 &&
2238	    ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA));
2239}
2240
2241int
2242ssl_check_srvr_ecc_cert_and_alg(SSL *s, X509 *x)
2243{
2244	const SSL_CIPHER *cs = s->s3->hs.cipher;
2245	unsigned long alg_a;
2246
2247	alg_a = cs->algorithm_auth;
2248
2249	if (alg_a & SSL_aECDSA) {
2250		/* Key usage, if present, must allow signing. */
2251		if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
2252			SSLerror(s, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2253			return (0);
2254		}
2255	}
2256
2257	return (1);
2258}
2259
2260SSL_CERT_PKEY *
2261ssl_get_server_send_pkey(const SSL *s)
2262{
2263	unsigned long alg_a;
2264	SSL_CERT *c;
2265	int i;
2266
2267	c = s->cert;
2268	ssl_set_cert_masks(c, s->s3->hs.cipher);
2269
2270	alg_a = s->s3->hs.cipher->algorithm_auth;
2271
2272	if (alg_a & SSL_aECDSA) {
2273		i = SSL_PKEY_ECC;
2274	} else if (alg_a & SSL_aRSA) {
2275		i = SSL_PKEY_RSA;
2276	} else if (alg_a & SSL_aGOST01) {
2277		i = SSL_PKEY_GOST01;
2278	} else { /* if (alg_a & SSL_aNULL) */
2279		SSLerror(s, ERR_R_INTERNAL_ERROR);
2280		return (NULL);
2281	}
2282
2283	return (c->pkeys + i);
2284}
2285
2286EVP_PKEY *
2287ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher, const EVP_MD **pmd,
2288    const struct ssl_sigalg **sap)
2289{
2290	const struct ssl_sigalg *sigalg = NULL;
2291	EVP_PKEY *pkey = NULL;
2292	unsigned long alg_a;
2293	SSL_CERT *c;
2294	int idx = -1;
2295
2296	alg_a = cipher->algorithm_auth;
2297	c = s->cert;
2298
2299	if (alg_a & SSL_aRSA) {
2300		idx = SSL_PKEY_RSA;
2301	} else if ((alg_a & SSL_aECDSA) &&
2302	    (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2303		idx = SSL_PKEY_ECC;
2304	if (idx == -1) {
2305		SSLerror(s, ERR_R_INTERNAL_ERROR);
2306		return (NULL);
2307	}
2308
2309	pkey = c->pkeys[idx].privatekey;
2310	if ((sigalg = ssl_sigalg_select(s, pkey)) == NULL) {
2311		SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2312		return (NULL);
2313	}
2314	*pmd = sigalg->md();
2315	*sap = sigalg;
2316
2317	return (pkey);
2318}
2319
2320size_t
2321ssl_dhe_params_auto_key_bits(SSL *s)
2322{
2323	SSL_CERT_PKEY *cpk;
2324	int key_bits;
2325
2326	if (s->cert->dhe_params_auto == 2) {
2327		key_bits = 1024;
2328	} else if (s->s3->hs.cipher->algorithm_auth & SSL_aNULL) {
2329		key_bits = 1024;
2330		if (s->s3->hs.cipher->strength_bits == 256)
2331			key_bits = 3072;
2332	} else {
2333		if ((cpk = ssl_get_server_send_pkey(s)) == NULL)
2334			return 0;
2335		if (cpk->privatekey == NULL ||
2336		    EVP_PKEY_get0_RSA(cpk->privatekey) == NULL)
2337			return 0;
2338		if ((key_bits = EVP_PKEY_bits(cpk->privatekey)) <= 0)
2339			return 0;
2340	}
2341
2342	return key_bits;
2343}
2344
2345static int
2346ssl_should_update_external_cache(SSL *s, int mode)
2347{
2348	int cache_mode;
2349
2350	cache_mode = s->session_ctx->internal->session_cache_mode;
2351
2352	/* Don't cache if mode says not to */
2353	if ((cache_mode & mode) == 0)
2354		return 0;
2355
2356	/* if it is not already cached, cache it */
2357	if (!s->internal->hit)
2358		return 1;
2359
2360	/* If it's TLS 1.3, do it to match OpenSSL */
2361	if (s->s3->hs.negotiated_tls_version >= TLS1_3_VERSION)
2362		return 1;
2363
2364	return 0;
2365}
2366
2367static int
2368ssl_should_update_internal_cache(SSL *s, int mode)
2369{
2370	int cache_mode;
2371
2372	cache_mode = s->session_ctx->internal->session_cache_mode;
2373
2374	/* Don't cache if mode says not to */
2375	if ((cache_mode & mode) == 0)
2376		return 0;
2377
2378	/* If it is already cached, don't cache it again */
2379	if (s->internal->hit)
2380		return 0;
2381
2382	if ((cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE) != 0)
2383		return 0;
2384
2385	/* If we are lesser than TLS 1.3, Cache it. */
2386	if (s->s3->hs.negotiated_tls_version < TLS1_3_VERSION)
2387		return 1;
2388
2389	/* Below this we consider TLS 1.3 or later */
2390
2391	/* If it's not a server, add it? OpenSSL does this. */
2392	if (!s->server)
2393		return 1;
2394
2395	/* XXX if we support early data / PSK need to add */
2396
2397	/*
2398	 * If we have the remove session callback, we will want
2399	 * to know about this even if it's a stateless ticket
2400	 * from 1.3 so we can know when it is removed.
2401	 */
2402	if (s->session_ctx->internal->remove_session_cb != NULL)
2403		return 1;
2404
2405	/* If we have set OP_NO_TICKET, cache it. */
2406	if ((s->internal->options & SSL_OP_NO_TICKET) != 0)
2407		return 1;
2408
2409	/* Otherwise do not cache */
2410	return 0;
2411}
2412
2413void
2414ssl_update_cache(SSL *s, int mode)
2415{
2416	int cache_mode, do_callback;
2417
2418	if (s->session->session_id_length == 0)
2419		return;
2420
2421	cache_mode = s->session_ctx->internal->session_cache_mode;
2422	do_callback = ssl_should_update_external_cache(s, mode);
2423
2424	if (ssl_should_update_internal_cache(s, mode)) {
2425		/*
2426		 * XXX should we fail if the add to the internal cache
2427		 * fails? OpenSSL doesn't care..
2428		 */
2429		(void) SSL_CTX_add_session(s->session_ctx, s->session);
2430	}
2431
2432	/*
2433	 * Update the "external cache" by calling the new session
2434	 * callback if present, even with TLS 1.3 without early data
2435	 * "because some application just want to know about the
2436	 * creation of a session and aren't doing a full cache".
2437	 * Apparently, if they are doing a full cache, they'll have
2438	 * some fun, but we endeavour to give application writers the
2439	 * same glorious experience they expect from OpenSSL which
2440	 * does it this way.
2441	 */
2442	if (do_callback && s->session_ctx->internal->new_session_cb != NULL) {
2443		    CRYPTO_add(&s->session->references, 1, CRYPTO_LOCK_SSL_SESSION);
2444		    if (!s->session_ctx->internal->new_session_cb(s, s->session))
2445			    SSL_SESSION_free(s->session);
2446	}
2447
2448	/* Auto flush every 255 connections. */
2449	if (!(cache_mode & SSL_SESS_CACHE_NO_AUTO_CLEAR) &&
2450	    (cache_mode & mode) != 0) {
2451		int connections;
2452		if (mode & SSL_SESS_CACHE_CLIENT)
2453			connections = s->session_ctx->internal->stats.sess_connect_good;
2454		else
2455			connections = s->session_ctx->internal->stats.sess_accept_good;
2456		if ((connections & 0xff) == 0xff)
2457			SSL_CTX_flush_sessions(s->session_ctx, time(NULL));
2458	}
2459}
2460
2461const SSL_METHOD *
2462SSL_get_ssl_method(SSL *s)
2463{
2464	return (s->method);
2465}
2466
2467int
2468SSL_set_ssl_method(SSL *s, const SSL_METHOD *method)
2469{
2470	int (*handshake_func)(SSL *) = NULL;
2471	int ret = 1;
2472
2473	if (s->method == method)
2474		return (ret);
2475
2476	if (s->internal->handshake_func == s->method->ssl_connect)
2477		handshake_func = method->ssl_connect;
2478	else if (s->internal->handshake_func == s->method->ssl_accept)
2479		handshake_func = method->ssl_accept;
2480
2481	if (s->method->version == method->version) {
2482		s->method = method;
2483	} else {
2484		s->method->ssl_free(s);
2485		s->method = method;
2486		ret = s->method->ssl_new(s);
2487	}
2488	s->internal->handshake_func = handshake_func;
2489
2490	return (ret);
2491}
2492
2493int
2494SSL_get_error(const SSL *s, int i)
2495{
2496	unsigned long l;
2497	int reason;
2498	BIO *bio;
2499
2500	if (i > 0)
2501		return (SSL_ERROR_NONE);
2502
2503	/*
2504	 * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake
2505	 * etc, where we do encode the error.
2506	 */
2507	if ((l = ERR_peek_error()) != 0) {
2508		if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2509			return (SSL_ERROR_SYSCALL);
2510		else
2511			return (SSL_ERROR_SSL);
2512	}
2513
2514	if (SSL_want_read(s)) {
2515		bio = SSL_get_rbio(s);
2516		if (BIO_should_read(bio)) {
2517			return (SSL_ERROR_WANT_READ);
2518		} else if (BIO_should_write(bio)) {
2519			/*
2520			 * This one doesn't make too much sense...  We never
2521			 * try to write to the rbio, and an application
2522			 * program where rbio and wbio are separate couldn't
2523			 * even know what it should wait for.  However if we
2524			 * ever set s->internal->rwstate incorrectly (so that we have
2525			 * SSL_want_read(s) instead of SSL_want_write(s))
2526			 * and rbio and wbio *are* the same, this test works
2527			 * around that bug; so it might be safer to keep it.
2528			 */
2529			return (SSL_ERROR_WANT_WRITE);
2530		} else if (BIO_should_io_special(bio)) {
2531			reason = BIO_get_retry_reason(bio);
2532			if (reason == BIO_RR_CONNECT)
2533				return (SSL_ERROR_WANT_CONNECT);
2534			else if (reason == BIO_RR_ACCEPT)
2535				return (SSL_ERROR_WANT_ACCEPT);
2536			else
2537				return (SSL_ERROR_SYSCALL); /* unknown */
2538		}
2539	}
2540
2541	if (SSL_want_write(s)) {
2542		bio = SSL_get_wbio(s);
2543		if (BIO_should_write(bio)) {
2544			return (SSL_ERROR_WANT_WRITE);
2545		} else if (BIO_should_read(bio)) {
2546			/*
2547			 * See above (SSL_want_read(s) with
2548			 * BIO_should_write(bio))
2549			 */
2550			return (SSL_ERROR_WANT_READ);
2551		} else if (BIO_should_io_special(bio)) {
2552			reason = BIO_get_retry_reason(bio);
2553			if (reason == BIO_RR_CONNECT)
2554				return (SSL_ERROR_WANT_CONNECT);
2555			else if (reason == BIO_RR_ACCEPT)
2556				return (SSL_ERROR_WANT_ACCEPT);
2557			else
2558				return (SSL_ERROR_SYSCALL);
2559		}
2560	}
2561
2562	if (SSL_want_x509_lookup(s))
2563		return (SSL_ERROR_WANT_X509_LOOKUP);
2564
2565	if ((s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2566	    (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
2567		return (SSL_ERROR_ZERO_RETURN);
2568
2569	return (SSL_ERROR_SYSCALL);
2570}
2571
2572int
2573SSL_do_handshake(SSL *s)
2574{
2575	if (s->internal->handshake_func == NULL) {
2576		SSLerror(s, SSL_R_CONNECTION_TYPE_NOT_SET);
2577		return (-1);
2578	}
2579
2580	s->method->ssl_renegotiate_check(s);
2581
2582	if (!SSL_in_init(s) && !SSL_in_before(s))
2583		return 1;
2584
2585	return s->internal->handshake_func(s);
2586}
2587
2588/*
2589 * For the next 2 functions, SSL_clear() sets shutdown and so
2590 * one of these calls will reset it
2591 */
2592void
2593SSL_set_accept_state(SSL *s)
2594{
2595	s->server = 1;
2596	s->internal->shutdown = 0;
2597	s->s3->hs.state = SSL_ST_ACCEPT|SSL_ST_BEFORE;
2598	s->internal->handshake_func = s->method->ssl_accept;
2599	ssl_clear_cipher_state(s);
2600}
2601
2602void
2603SSL_set_connect_state(SSL *s)
2604{
2605	s->server = 0;
2606	s->internal->shutdown = 0;
2607	s->s3->hs.state = SSL_ST_CONNECT|SSL_ST_BEFORE;
2608	s->internal->handshake_func = s->method->ssl_connect;
2609	ssl_clear_cipher_state(s);
2610}
2611
2612int
2613ssl_undefined_function(SSL *s)
2614{
2615	SSLerror(s, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2616	return (0);
2617}
2618
2619int
2620ssl_undefined_void_function(void)
2621{
2622	SSLerrorx(ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2623	return (0);
2624}
2625
2626int
2627ssl_undefined_const_function(const SSL *s)
2628{
2629	SSLerror(s, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2630	return (0);
2631}
2632
2633const char *
2634ssl_version_string(int ver)
2635{
2636	switch (ver) {
2637	case TLS1_VERSION:
2638		return (SSL_TXT_TLSV1);
2639	case TLS1_1_VERSION:
2640		return (SSL_TXT_TLSV1_1);
2641	case TLS1_2_VERSION:
2642		return (SSL_TXT_TLSV1_2);
2643	case TLS1_3_VERSION:
2644		return (SSL_TXT_TLSV1_3);
2645	case DTLS1_VERSION:
2646		return (SSL_TXT_DTLS1);
2647	case DTLS1_2_VERSION:
2648		return (SSL_TXT_DTLS1_2);
2649	default:
2650		return ("unknown");
2651	}
2652}
2653
2654const char *
2655SSL_get_version(const SSL *s)
2656{
2657	return ssl_version_string(s->version);
2658}
2659
2660SSL *
2661SSL_dup(SSL *s)
2662{
2663	STACK_OF(X509_NAME) *sk;
2664	X509_NAME *xn;
2665	SSL *ret;
2666	int i;
2667
2668	if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
2669		goto err;
2670
2671	ret->version = s->version;
2672	ret->method = s->method;
2673
2674	if (s->session != NULL) {
2675		if (!SSL_copy_session_id(ret, s))
2676			goto err;
2677	} else {
2678		/*
2679		 * No session has been established yet, so we have to expect
2680		 * that s->cert or ret->cert will be changed later --
2681		 * they should not both point to the same object,
2682		 * and thus we can't use SSL_copy_session_id.
2683		 */
2684
2685		ret->method->ssl_free(ret);
2686		ret->method = s->method;
2687		ret->method->ssl_new(ret);
2688
2689		ssl_cert_free(ret->cert);
2690		if ((ret->cert = ssl_cert_dup(s->cert)) == NULL)
2691			goto err;
2692
2693		if (!SSL_set_session_id_context(ret, s->sid_ctx,
2694		    s->sid_ctx_length))
2695			goto err;
2696	}
2697
2698	ret->internal->options = s->internal->options;
2699	ret->internal->mode = s->internal->mode;
2700	SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
2701	SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
2702	ret->internal->msg_callback = s->internal->msg_callback;
2703	ret->internal->msg_callback_arg = s->internal->msg_callback_arg;
2704	SSL_set_verify(ret, SSL_get_verify_mode(s),
2705	SSL_get_verify_callback(s));
2706	SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
2707	ret->internal->generate_session_id = s->internal->generate_session_id;
2708
2709	SSL_set_info_callback(ret, SSL_get_info_callback(s));
2710
2711	ret->internal->debug = s->internal->debug;
2712
2713	/* copy app data, a little dangerous perhaps */
2714	if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL,
2715	    &ret->internal->ex_data, &s->internal->ex_data))
2716		goto err;
2717
2718	/* setup rbio, and wbio */
2719	if (s->rbio != NULL) {
2720		if (!BIO_dup_state(s->rbio,(char *)&ret->rbio))
2721			goto err;
2722	}
2723	if (s->wbio != NULL) {
2724		if (s->wbio != s->rbio) {
2725			if (!BIO_dup_state(s->wbio,(char *)&ret->wbio))
2726				goto err;
2727		} else
2728			ret->wbio = ret->rbio;
2729	}
2730	ret->internal->rwstate = s->internal->rwstate;
2731	ret->internal->in_handshake = s->internal->in_handshake;
2732	ret->internal->handshake_func = s->internal->handshake_func;
2733	ret->server = s->server;
2734	ret->internal->renegotiate = s->internal->renegotiate;
2735	ret->internal->new_session = s->internal->new_session;
2736	ret->internal->quiet_shutdown = s->internal->quiet_shutdown;
2737	ret->internal->shutdown = s->internal->shutdown;
2738	/* SSL_dup does not really work at any state, though */
2739	ret->s3->hs.state = s->s3->hs.state;
2740	ret->internal->rstate = s->internal->rstate;
2741
2742	/*
2743	 * Would have to copy ret->init_buf, ret->init_msg, ret->init_num,
2744	 * ret->init_off
2745	 */
2746	ret->internal->init_num = 0;
2747
2748	ret->internal->hit = s->internal->hit;
2749
2750	X509_VERIFY_PARAM_inherit(ret->param, s->param);
2751
2752	if (s->cipher_list != NULL) {
2753		if ((ret->cipher_list =
2754		    sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
2755			goto err;
2756	}
2757	if (s->internal->cipher_list_tls13 != NULL) {
2758		if ((ret->internal->cipher_list_tls13 =
2759		    sk_SSL_CIPHER_dup(s->internal->cipher_list_tls13)) == NULL)
2760			goto err;
2761	}
2762
2763	/* Dup the client_CA list */
2764	if (s->internal->client_CA != NULL) {
2765		if ((sk = sk_X509_NAME_dup(s->internal->client_CA)) == NULL) goto err;
2766			ret->internal->client_CA = sk;
2767		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2768			xn = sk_X509_NAME_value(sk, i);
2769			if (sk_X509_NAME_set(sk, i,
2770			    X509_NAME_dup(xn)) == NULL) {
2771				X509_NAME_free(xn);
2772				goto err;
2773			}
2774		}
2775	}
2776
2777	return ret;
2778 err:
2779	SSL_free(ret);
2780	return NULL;
2781}
2782
2783void
2784ssl_clear_cipher_state(SSL *s)
2785{
2786	tls12_record_layer_clear_read_state(s->internal->rl);
2787	tls12_record_layer_clear_write_state(s->internal->rl);
2788}
2789
2790void
2791ssl_info_callback(const SSL *s, int type, int value)
2792{
2793	ssl_info_callback_fn *cb;
2794
2795	if ((cb = s->internal->info_callback) == NULL)
2796		cb = s->ctx->internal->info_callback;
2797	if (cb != NULL)
2798		cb(s, type, value);
2799}
2800
2801void
2802ssl_msg_callback(SSL *s, int is_write, int content_type,
2803    const void *msg_buf, size_t msg_len)
2804{
2805	if (s->internal->msg_callback != NULL)
2806		s->internal->msg_callback(is_write, s->version, content_type,
2807		    msg_buf, msg_len, s, s->internal->msg_callback_arg);
2808}
2809
2810/* Fix this function so that it takes an optional type parameter */
2811X509 *
2812SSL_get_certificate(const SSL *s)
2813{
2814	return (s->cert->key->x509);
2815}
2816
2817/* Fix this function so that it takes an optional type parameter */
2818EVP_PKEY *
2819SSL_get_privatekey(const SSL *s)
2820{
2821	return (s->cert->key->privatekey);
2822}
2823
2824const SSL_CIPHER *
2825SSL_get_current_cipher(const SSL *s)
2826{
2827	if ((s->session != NULL) && (s->session->cipher != NULL))
2828		return (s->session->cipher);
2829	return (NULL);
2830}
2831const void *
2832SSL_get_current_compression(SSL *s)
2833{
2834	return (NULL);
2835}
2836
2837const void *
2838SSL_get_current_expansion(SSL *s)
2839{
2840	return (NULL);
2841}
2842
2843size_t
2844SSL_get_client_random(const SSL *s, unsigned char *out, size_t max_out)
2845{
2846	size_t len = sizeof(s->s3->client_random);
2847
2848	if (out == NULL)
2849		return len;
2850
2851	if (len > max_out)
2852		len = max_out;
2853
2854	memcpy(out, s->s3->client_random, len);
2855
2856	return len;
2857}
2858
2859size_t
2860SSL_get_server_random(const SSL *s, unsigned char *out, size_t max_out)
2861{
2862	size_t len = sizeof(s->s3->server_random);
2863
2864	if (out == NULL)
2865		return len;
2866
2867	if (len > max_out)
2868		len = max_out;
2869
2870	memcpy(out, s->s3->server_random, len);
2871
2872	return len;
2873}
2874
2875int
2876ssl_init_wbio_buffer(SSL *s, int push)
2877{
2878	BIO	*bbio;
2879
2880	if (s->bbio == NULL) {
2881		bbio = BIO_new(BIO_f_buffer());
2882		if (bbio == NULL)
2883			return (0);
2884		s->bbio = bbio;
2885	} else {
2886		bbio = s->bbio;
2887		if (s->bbio == s->wbio)
2888			s->wbio = BIO_pop(s->wbio);
2889	}
2890	(void)BIO_reset(bbio);
2891/*	if (!BIO_set_write_buffer_size(bbio,16*1024)) */
2892	if (!BIO_set_read_buffer_size(bbio, 1)) {
2893		SSLerror(s, ERR_R_BUF_LIB);
2894		return (0);
2895	}
2896	if (push) {
2897		if (s->wbio != bbio)
2898			s->wbio = BIO_push(bbio, s->wbio);
2899	} else {
2900		if (s->wbio == bbio)
2901			s->wbio = BIO_pop(bbio);
2902	}
2903	return (1);
2904}
2905
2906void
2907ssl_free_wbio_buffer(SSL *s)
2908{
2909	if (s == NULL)
2910		return;
2911
2912	if (s->bbio == NULL)
2913		return;
2914
2915	if (s->bbio == s->wbio) {
2916		/* remove buffering */
2917		s->wbio = BIO_pop(s->wbio);
2918	}
2919	BIO_free(s->bbio);
2920	s->bbio = NULL;
2921}
2922
2923void
2924SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
2925{
2926	ctx->internal->quiet_shutdown = mode;
2927}
2928
2929int
2930SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
2931{
2932	return (ctx->internal->quiet_shutdown);
2933}
2934
2935void
2936SSL_set_quiet_shutdown(SSL *s, int mode)
2937{
2938	s->internal->quiet_shutdown = mode;
2939}
2940
2941int
2942SSL_get_quiet_shutdown(const SSL *s)
2943{
2944	return (s->internal->quiet_shutdown);
2945}
2946
2947void
2948SSL_set_shutdown(SSL *s, int mode)
2949{
2950	s->internal->shutdown = mode;
2951}
2952
2953int
2954SSL_get_shutdown(const SSL *s)
2955{
2956	return (s->internal->shutdown);
2957}
2958
2959int
2960SSL_version(const SSL *s)
2961{
2962	return (s->version);
2963}
2964
2965SSL_CTX *
2966SSL_get_SSL_CTX(const SSL *ssl)
2967{
2968	return (ssl->ctx);
2969}
2970
2971SSL_CTX *
2972SSL_set_SSL_CTX(SSL *ssl, SSL_CTX* ctx)
2973{
2974	SSL_CERT *new_cert;
2975
2976	if (ctx == NULL)
2977		ctx = ssl->initial_ctx;
2978	if (ssl->ctx == ctx)
2979		return (ssl->ctx);
2980
2981	if ((new_cert = ssl_cert_dup(ctx->internal->cert)) == NULL)
2982		return NULL;
2983	ssl_cert_free(ssl->cert);
2984	ssl->cert = new_cert;
2985
2986	SSL_CTX_up_ref(ctx);
2987	SSL_CTX_free(ssl->ctx); /* decrement reference count */
2988	ssl->ctx = ctx;
2989
2990	return (ssl->ctx);
2991}
2992
2993int
2994SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
2995{
2996	return (X509_STORE_set_default_paths(ctx->cert_store));
2997}
2998
2999int
3000SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
3001    const char *CApath)
3002{
3003	return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
3004}
3005
3006int
3007SSL_CTX_load_verify_mem(SSL_CTX *ctx, void *buf, int len)
3008{
3009	return (X509_STORE_load_mem(ctx->cert_store, buf, len));
3010}
3011
3012void
3013SSL_set_info_callback(SSL *ssl, void (*cb)(const SSL *ssl, int type, int val))
3014{
3015	ssl->internal->info_callback = cb;
3016}
3017
3018void (*SSL_get_info_callback(const SSL *ssl))(const SSL *ssl, int type, int val)
3019{
3020	return (ssl->internal->info_callback);
3021}
3022
3023int
3024SSL_state(const SSL *ssl)
3025{
3026	return (ssl->s3->hs.state);
3027}
3028
3029void
3030SSL_set_state(SSL *ssl, int state)
3031{
3032	ssl->s3->hs.state = state;
3033}
3034
3035void
3036SSL_set_verify_result(SSL *ssl, long arg)
3037{
3038	ssl->verify_result = arg;
3039}
3040
3041long
3042SSL_get_verify_result(const SSL *ssl)
3043{
3044	return (ssl->verify_result);
3045}
3046
3047int
3048SSL_verify_client_post_handshake(SSL *ssl)
3049{
3050	return 0;
3051}
3052
3053void
3054SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val)
3055{
3056	return;
3057}
3058
3059void
3060SSL_set_post_handshake_auth(SSL *ssl, int val)
3061{
3062	return;
3063}
3064
3065int
3066SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
3067    CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
3068{
3069	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp,
3070	    new_func, dup_func, free_func));
3071}
3072
3073int
3074SSL_set_ex_data(SSL *s, int idx, void *arg)
3075{
3076	return (CRYPTO_set_ex_data(&s->internal->ex_data, idx, arg));
3077}
3078
3079void *
3080SSL_get_ex_data(const SSL *s, int idx)
3081{
3082	return (CRYPTO_get_ex_data(&s->internal->ex_data, idx));
3083}
3084
3085int
3086SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
3087    CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
3088{
3089	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp,
3090	    new_func, dup_func, free_func));
3091}
3092
3093int
3094SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
3095{
3096	return (CRYPTO_set_ex_data(&s->internal->ex_data, idx, arg));
3097}
3098
3099void *
3100SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
3101{
3102	return (CRYPTO_get_ex_data(&s->internal->ex_data, idx));
3103}
3104
3105int
3106ssl_ok(SSL *s)
3107{
3108	return (1);
3109}
3110
3111X509_STORE *
3112SSL_CTX_get_cert_store(const SSL_CTX *ctx)
3113{
3114	return (ctx->cert_store);
3115}
3116
3117void
3118SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
3119{
3120	X509_STORE_free(ctx->cert_store);
3121	ctx->cert_store = store;
3122}
3123
3124X509 *
3125SSL_CTX_get0_certificate(const SSL_CTX *ctx)
3126{
3127	if (ctx->internal->cert == NULL)
3128		return NULL;
3129
3130	return ctx->internal->cert->key->x509;
3131}
3132
3133EVP_PKEY *
3134SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
3135{
3136	if (ctx->internal->cert == NULL)
3137		return NULL;
3138
3139	return ctx->internal->cert->key->privatekey;
3140}
3141
3142int
3143SSL_want(const SSL *s)
3144{
3145	return (s->internal->rwstate);
3146}
3147
3148void
3149SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*cb)(SSL *ssl, int is_export,
3150    int keylength))
3151{
3152	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
3153}
3154
3155void
3156SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb)(SSL *ssl, int is_export,
3157    int keylength))
3158{
3159	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
3160}
3161
3162void
3163SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx, DH *(*dh)(SSL *ssl, int is_export,
3164    int keylength))
3165{
3166	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
3167}
3168
3169void
3170SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh)(SSL *ssl, int is_export,
3171    int keylength))
3172{
3173	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
3174}
3175
3176void
3177SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx, EC_KEY *(*ecdh)(SSL *ssl,
3178    int is_export, int keylength))
3179{
3180	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH_CB,
3181	    (void (*)(void))ecdh);
3182}
3183
3184void
3185SSL_set_tmp_ecdh_callback(SSL *ssl, EC_KEY *(*ecdh)(SSL *ssl, int is_export,
3186    int keylength))
3187{
3188	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH_CB,(void (*)(void))ecdh);
3189}
3190
3191
3192void
3193SSL_CTX_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version,
3194    int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
3195{
3196	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK,
3197	    (void (*)(void))cb);
3198}
3199
3200void
3201SSL_set_msg_callback(SSL *ssl, void (*cb)(int write_p, int version,
3202    int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
3203{
3204	SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3205}
3206
3207void
3208SSL_set_debug(SSL *s, int debug)
3209{
3210	s->internal->debug = debug;
3211}
3212
3213int
3214SSL_cache_hit(SSL *s)
3215{
3216	return (s->internal->hit);
3217}
3218
3219int
3220SSL_CTX_get_min_proto_version(SSL_CTX *ctx)
3221{
3222	return ctx->internal->min_proto_version;
3223}
3224
3225int
3226SSL_CTX_set_min_proto_version(SSL_CTX *ctx, uint16_t version)
3227{
3228	return ssl_version_set_min(ctx->method, version,
3229	    ctx->internal->max_tls_version, &ctx->internal->min_tls_version,
3230	    &ctx->internal->min_proto_version);
3231}
3232
3233int
3234SSL_CTX_get_max_proto_version(SSL_CTX *ctx)
3235{
3236	return ctx->internal->max_proto_version;
3237}
3238
3239int
3240SSL_CTX_set_max_proto_version(SSL_CTX *ctx, uint16_t version)
3241{
3242	return ssl_version_set_max(ctx->method, version,
3243	    ctx->internal->min_tls_version, &ctx->internal->max_tls_version,
3244	    &ctx->internal->max_proto_version);
3245}
3246
3247int
3248SSL_get_min_proto_version(SSL *ssl)
3249{
3250	return ssl->internal->min_proto_version;
3251}
3252
3253int
3254SSL_set_min_proto_version(SSL *ssl, uint16_t version)
3255{
3256	return ssl_version_set_min(ssl->method, version,
3257	    ssl->internal->max_tls_version, &ssl->internal->min_tls_version,
3258	    &ssl->internal->min_proto_version);
3259}
3260int
3261SSL_get_max_proto_version(SSL *ssl)
3262{
3263	return ssl->internal->max_proto_version;
3264}
3265
3266int
3267SSL_set_max_proto_version(SSL *ssl, uint16_t version)
3268{
3269	return ssl_version_set_max(ssl->method, version,
3270	    ssl->internal->min_tls_version, &ssl->internal->max_tls_version,
3271	    &ssl->internal->max_proto_version);
3272}
3273
3274const SSL_METHOD *
3275SSL_CTX_get_ssl_method(const SSL_CTX *ctx)
3276{
3277	return ctx->method;
3278}
3279
3280int
3281SSL_CTX_get_security_level(const SSL_CTX *ctx)
3282{
3283	return ctx->internal->cert->security_level;
3284}
3285
3286void
3287SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
3288{
3289	ctx->internal->cert->security_level = level;
3290}
3291
3292int
3293SSL_get_security_level(const SSL *ssl)
3294{
3295	return ssl->cert->security_level;
3296}
3297
3298void
3299SSL_set_security_level(SSL *ssl, int level)
3300{
3301	ssl->cert->security_level = level;
3302}
3303
3304int
3305SSL_is_quic(const SSL *ssl)
3306{
3307	return ssl->quic_method != NULL;
3308}
3309
3310int
3311SSL_set_quic_transport_params(SSL *ssl, const uint8_t *params,
3312    size_t params_len)
3313{
3314	freezero(ssl->internal->quic_transport_params,
3315	    ssl->internal->quic_transport_params_len);
3316	ssl->internal->quic_transport_params = NULL;
3317	ssl->internal->quic_transport_params_len = 0;
3318
3319	if ((ssl->internal->quic_transport_params = malloc(params_len)) == NULL)
3320		return 0;
3321
3322	memcpy(ssl->internal->quic_transport_params, params, params_len);
3323	ssl->internal->quic_transport_params_len = params_len;
3324
3325	return 1;
3326}
3327
3328void
3329SSL_get_peer_quic_transport_params(const SSL *ssl, const uint8_t **out_params,
3330    size_t *out_params_len)
3331{
3332	*out_params = ssl->s3->peer_quic_transport_params;
3333	*out_params_len = ssl->s3->peer_quic_transport_params_len;
3334}
3335
3336static int
3337ssl_cipher_id_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_)
3338{
3339	SSL_CIPHER const *a = a_;
3340	SSL_CIPHER const *b = b_;
3341	return ssl_cipher_id_cmp(a, b);
3342}
3343
3344SSL_CIPHER *
3345OBJ_bsearch_ssl_cipher_id(SSL_CIPHER *key, SSL_CIPHER const *base, int num)
3346{
3347	return (SSL_CIPHER *)OBJ_bsearch_(key, base, num, sizeof(SSL_CIPHER),
3348	    ssl_cipher_id_cmp_BSEARCH_CMP_FN);
3349}
3350