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