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