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