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