xref: /openbsd-src/lib/libssl/ssl_lib.c (revision de8cc8edbc71bd3e3bc7fbffa27ba0e564c37d8b)
1 /* $OpenBSD: ssl_lib.c,v 1.250 2021/02/27 14:20:50 jsing Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECC cipher suite support in OpenSSL originally developed by
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116 /* ====================================================================
117  * Copyright 2005 Nokia. All rights reserved.
118  *
119  * The portions of the attached software ("Contribution") is developed by
120  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
121  * license.
122  *
123  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
124  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
125  * support (see RFC 4279) to OpenSSL.
126  *
127  * No patent licenses or other rights except those expressly stated in
128  * the OpenSSL open source license shall be deemed granted or received
129  * expressly, by implication, estoppel, or otherwise.
130  *
131  * No assurances are provided by Nokia that the Contribution does not
132  * infringe the patent or other intellectual property rights of any third
133  * party or that the license provides you with all the necessary rights
134  * to make use of the Contribution.
135  *
136  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
137  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
138  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
139  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
140  * OTHERWISE.
141  */
142 
143 #include <arpa/inet.h>
144 #include <sys/socket.h>
145 #include <netinet/in.h>
146 
147 #include <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 
165 const char *SSL_version_str = OPENSSL_VERSION_TEXT;
166 
167 int
168 SSL_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 */
222 int
223 SSL_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 
238 SSL *
239 SSL_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_tls_version = ctx->internal->min_tls_version;
258 	s->internal->max_tls_version = ctx->internal->max_tls_version;
259 	s->internal->min_proto_version = ctx->internal->min_proto_version;
260 	s->internal->max_proto_version = ctx->internal->max_proto_version;
261 
262 	s->internal->options = ctx->internal->options;
263 	s->internal->mode = ctx->internal->mode;
264 	s->internal->max_cert_list = ctx->internal->max_cert_list;
265 
266 	if ((s->cert = ssl_cert_dup(ctx->internal->cert)) == NULL)
267 		goto err;
268 
269 	s->internal->read_ahead = ctx->internal->read_ahead;
270 	s->internal->msg_callback = ctx->internal->msg_callback;
271 	s->internal->msg_callback_arg = ctx->internal->msg_callback_arg;
272 	s->verify_mode = ctx->verify_mode;
273 	s->sid_ctx_length = ctx->sid_ctx_length;
274 	OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx);
275 	memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
276 	s->internal->verify_callback = ctx->internal->default_verify_callback;
277 	s->internal->generate_session_id = ctx->internal->generate_session_id;
278 
279 	s->param = X509_VERIFY_PARAM_new();
280 	if (!s->param)
281 		goto err;
282 	X509_VERIFY_PARAM_inherit(s->param, ctx->param);
283 	s->internal->quiet_shutdown = ctx->internal->quiet_shutdown;
284 	s->max_send_fragment = ctx->internal->max_send_fragment;
285 
286 	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
287 	s->ctx = ctx;
288 	s->internal->tlsext_debug_cb = 0;
289 	s->internal->tlsext_debug_arg = NULL;
290 	s->internal->tlsext_ticket_expected = 0;
291 	s->tlsext_status_type = -1;
292 	s->internal->tlsext_status_expected = 0;
293 	s->internal->tlsext_ocsp_ids = NULL;
294 	s->internal->tlsext_ocsp_exts = NULL;
295 	s->internal->tlsext_ocsp_resp = NULL;
296 	s->internal->tlsext_ocsp_resp_len = 0;
297 	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
298 	s->initial_ctx = ctx;
299 
300 	if (ctx->internal->tlsext_ecpointformatlist != NULL) {
301 		s->internal->tlsext_ecpointformatlist =
302 		    calloc(ctx->internal->tlsext_ecpointformatlist_length,
303 			sizeof(ctx->internal->tlsext_ecpointformatlist[0]));
304 		if (s->internal->tlsext_ecpointformatlist == NULL)
305 			goto err;
306 		memcpy(s->internal->tlsext_ecpointformatlist,
307 		    ctx->internal->tlsext_ecpointformatlist,
308 		    ctx->internal->tlsext_ecpointformatlist_length *
309 		    sizeof(ctx->internal->tlsext_ecpointformatlist[0]));
310 		s->internal->tlsext_ecpointformatlist_length =
311 		    ctx->internal->tlsext_ecpointformatlist_length;
312 	}
313 	if (ctx->internal->tlsext_supportedgroups != NULL) {
314 		s->internal->tlsext_supportedgroups =
315 		    calloc(ctx->internal->tlsext_supportedgroups_length,
316 			sizeof(ctx->internal->tlsext_supportedgroups[0]));
317 		if (s->internal->tlsext_supportedgroups == NULL)
318 			goto err;
319 		memcpy(s->internal->tlsext_supportedgroups,
320 		    ctx->internal->tlsext_supportedgroups,
321 		    ctx->internal->tlsext_supportedgroups_length *
322 		    sizeof(ctx->internal->tlsext_supportedgroups[0]));
323 		s->internal->tlsext_supportedgroups_length =
324 		    ctx->internal->tlsext_supportedgroups_length;
325 	}
326 
327 	if (s->ctx->internal->alpn_client_proto_list != NULL) {
328 		s->internal->alpn_client_proto_list =
329 		    malloc(s->ctx->internal->alpn_client_proto_list_len);
330 		if (s->internal->alpn_client_proto_list == NULL)
331 			goto err;
332 		memcpy(s->internal->alpn_client_proto_list,
333 		    s->ctx->internal->alpn_client_proto_list,
334 		    s->ctx->internal->alpn_client_proto_list_len);
335 		s->internal->alpn_client_proto_list_len =
336 		    s->ctx->internal->alpn_client_proto_list_len;
337 	}
338 
339 	s->verify_result = X509_V_OK;
340 
341 	s->method = ctx->method;
342 
343 	if (!s->method->internal->ssl_new(s))
344 		goto err;
345 
346 	if ((s->internal->rl = tls12_record_layer_new()) == NULL)
347 		goto err;
348 
349 	s->references = 1;
350 	s->server = ctx->method->internal->server;
351 
352 	SSL_clear(s);
353 
354 	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->internal->ex_data);
355 
356 	return (s);
357 
358  err:
359 	SSL_free(s);
360 	SSLerrorx(ERR_R_MALLOC_FAILURE);
361 	return (NULL);
362 }
363 
364 int
365 SSL_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 
378 int
379 SSL_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 
392 int
393 SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
394 {
395 	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
396 	ctx->internal->generate_session_id = cb;
397 	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
398 	return (1);
399 }
400 
401 int
402 SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
403 {
404 	CRYPTO_w_lock(CRYPTO_LOCK_SSL);
405 	ssl->internal->generate_session_id = cb;
406 	CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
407 	return (1);
408 }
409 
410 int
411 SSL_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->internal->sessions, &r);
432 	CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
433 	return (p != NULL);
434 }
435 
436 int
437 SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
438 {
439 	return (X509_VERIFY_PARAM_set_purpose(s->param, purpose));
440 }
441 
442 int
443 SSL_set_purpose(SSL *s, int purpose)
444 {
445 	return (X509_VERIFY_PARAM_set_purpose(s->param, purpose));
446 }
447 
448 int
449 SSL_CTX_set_trust(SSL_CTX *s, int trust)
450 {
451 	return (X509_VERIFY_PARAM_set_trust(s->param, trust));
452 }
453 
454 int
455 SSL_set_trust(SSL *s, int trust)
456 {
457 	return (X509_VERIFY_PARAM_set_trust(s->param, trust));
458 }
459 
460 int
461 SSL_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 
474 void
475 SSL_set_hostflags(SSL *s, unsigned int flags)
476 {
477 	X509_VERIFY_PARAM_set_hostflags(s->param, flags);
478 }
479 
480 const char *
481 SSL_get0_peername(SSL *s)
482 {
483 	return X509_VERIFY_PARAM_get0_peername(s->param);
484 }
485 
486 X509_VERIFY_PARAM *
487 SSL_CTX_get0_param(SSL_CTX *ctx)
488 {
489 	return (ctx->param);
490 }
491 
492 int
493 SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
494 {
495 	return (X509_VERIFY_PARAM_set1(ctx->param, vpm));
496 }
497 
498 X509_VERIFY_PARAM *
499 SSL_get0_param(SSL *ssl)
500 {
501 	return (ssl->param);
502 }
503 
504 int
505 SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
506 {
507 	return (X509_VERIFY_PARAM_set1(ssl->param, vpm));
508 }
509 
510 void
511 SSL_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->internal->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->internal->tls13);
540 
541 	ssl3_release_init_buffer(s);
542 
543 	sk_SSL_CIPHER_free(s->cipher_list);
544 	sk_SSL_CIPHER_free(s->internal->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_hostname);
557 	SSL_CTX_free(s->initial_ctx);
558 
559 	free(s->internal->tlsext_ecpointformatlist);
560 	free(s->internal->tlsext_supportedgroups);
561 
562 	sk_X509_EXTENSION_pop_free(s->internal->tlsext_ocsp_exts,
563 	    X509_EXTENSION_free);
564 	sk_OCSP_RESPID_pop_free(s->internal->tlsext_ocsp_ids, OCSP_RESPID_free);
565 	free(s->internal->tlsext_ocsp_resp);
566 
567 	sk_X509_NAME_pop_free(s->internal->client_CA, X509_NAME_free);
568 
569 	if (s->method != NULL)
570 		s->method->internal->ssl_free(s);
571 
572 	SSL_CTX_free(s->ctx);
573 
574 	free(s->internal->alpn_client_proto_list);
575 
576 #ifndef OPENSSL_NO_SRTP
577 	sk_SRTP_PROTECTION_PROFILE_free(s->internal->srtp_profiles);
578 #endif
579 
580 	tls12_record_layer_free(s->internal->rl);
581 
582 	free(s->internal);
583 	free(s);
584 }
585 
586 int
587 SSL_up_ref(SSL *s)
588 {
589 	int refs = CRYPTO_add(&s->references, 1, CRYPTO_LOCK_SSL);
590 	return (refs > 1) ? 1 : 0;
591 }
592 
593 void
594 SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
595 {
596 	/* If the output buffering BIO is still in place, remove it */
597 	if (s->bbio != NULL) {
598 		if (s->wbio == s->bbio) {
599 			s->wbio = s->wbio->next_bio;
600 			s->bbio->next_bio = NULL;
601 		}
602 	}
603 
604 	if (s->rbio != rbio && s->rbio != s->wbio)
605 		BIO_free_all(s->rbio);
606 	if (s->wbio != wbio)
607 		BIO_free_all(s->wbio);
608 	s->rbio = rbio;
609 	s->wbio = wbio;
610 }
611 
612 BIO *
613 SSL_get_rbio(const SSL *s)
614 {
615 	return (s->rbio);
616 }
617 
618 BIO *
619 SSL_get_wbio(const SSL *s)
620 {
621 	return (s->wbio);
622 }
623 
624 int
625 SSL_get_fd(const SSL *s)
626 {
627 	return (SSL_get_rfd(s));
628 }
629 
630 int
631 SSL_get_rfd(const SSL *s)
632 {
633 	int	 ret = -1;
634 	BIO	*b, *r;
635 
636 	b = SSL_get_rbio(s);
637 	r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
638 	if (r != NULL)
639 		BIO_get_fd(r, &ret);
640 	return (ret);
641 }
642 
643 int
644 SSL_get_wfd(const SSL *s)
645 {
646 	int	 ret = -1;
647 	BIO	*b, *r;
648 
649 	b = SSL_get_wbio(s);
650 	r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
651 	if (r != NULL)
652 		BIO_get_fd(r, &ret);
653 	return (ret);
654 }
655 
656 int
657 SSL_set_fd(SSL *s, int fd)
658 {
659 	int	 ret = 0;
660 	BIO	*bio = NULL;
661 
662 	bio = BIO_new(BIO_s_socket());
663 
664 	if (bio == NULL) {
665 		SSLerror(s, ERR_R_BUF_LIB);
666 		goto err;
667 	}
668 	BIO_set_fd(bio, fd, BIO_NOCLOSE);
669 	SSL_set_bio(s, bio, bio);
670 	ret = 1;
671 err:
672 	return (ret);
673 }
674 
675 int
676 SSL_set_wfd(SSL *s, int fd)
677 {
678 	int	 ret = 0;
679 	BIO	*bio = NULL;
680 
681 	if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET)
682 	    || ((int)BIO_get_fd(s->rbio, NULL) != fd)) {
683 		bio = BIO_new(BIO_s_socket());
684 
685 		if (bio == NULL) {
686 			SSLerror(s, ERR_R_BUF_LIB);
687 			goto err;
688 		}
689 		BIO_set_fd(bio, fd, BIO_NOCLOSE);
690 		SSL_set_bio(s, SSL_get_rbio(s), bio);
691 	} else
692 		SSL_set_bio(s, SSL_get_rbio(s), SSL_get_rbio(s));
693 	ret = 1;
694 err:
695 	return (ret);
696 }
697 
698 int
699 SSL_set_rfd(SSL *s, int fd)
700 {
701 	int	 ret = 0;
702 	BIO	*bio = NULL;
703 
704 	if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET)
705 	    || ((int)BIO_get_fd(s->wbio, NULL) != fd)) {
706 		bio = BIO_new(BIO_s_socket());
707 
708 		if (bio == NULL) {
709 			SSLerror(s, ERR_R_BUF_LIB);
710 			goto err;
711 		}
712 		BIO_set_fd(bio, fd, BIO_NOCLOSE);
713 		SSL_set_bio(s, bio, SSL_get_wbio(s));
714 	} else
715 		SSL_set_bio(s, SSL_get_wbio(s), SSL_get_wbio(s));
716 	ret = 1;
717 err:
718 	return (ret);
719 }
720 
721 
722 /* return length of latest Finished message we sent, copy to 'buf' */
723 size_t
724 SSL_get_finished(const SSL *s, void *buf, size_t count)
725 {
726 	size_t	ret;
727 
728 	ret = S3I(s)->tmp.finish_md_len;
729 	if (count > ret)
730 		count = ret;
731 	memcpy(buf, S3I(s)->tmp.finish_md, count);
732 	return (ret);
733 }
734 
735 /* return length of latest Finished message we expected, copy to 'buf' */
736 size_t
737 SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
738 {
739 	size_t	ret;
740 
741 	ret = S3I(s)->tmp.peer_finish_md_len;
742 	if (count > ret)
743 		count = ret;
744 	memcpy(buf, S3I(s)->tmp.peer_finish_md, count);
745 	return (ret);
746 }
747 
748 
749 int
750 SSL_get_verify_mode(const SSL *s)
751 {
752 	return (s->verify_mode);
753 }
754 
755 int
756 SSL_get_verify_depth(const SSL *s)
757 {
758 	return (X509_VERIFY_PARAM_get_depth(s->param));
759 }
760 
761 int
762 (*SSL_get_verify_callback(const SSL *s))(int, X509_STORE_CTX *)
763 {
764 	return (s->internal->verify_callback);
765 }
766 
767 int
768 SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
769 {
770 	return (ctx->verify_mode);
771 }
772 
773 int
774 SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
775 {
776 	return (X509_VERIFY_PARAM_get_depth(ctx->param));
777 }
778 
779 int
780 (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))(int, X509_STORE_CTX *)
781 {
782 	return (ctx->internal->default_verify_callback);
783 }
784 
785 void
786 SSL_set_verify(SSL *s, int mode,
787     int (*callback)(int ok, X509_STORE_CTX *ctx))
788 {
789 	s->verify_mode = mode;
790 	if (callback != NULL)
791 		s->internal->verify_callback = callback;
792 }
793 
794 void
795 SSL_set_verify_depth(SSL *s, int depth)
796 {
797 	X509_VERIFY_PARAM_set_depth(s->param, depth);
798 }
799 
800 void
801 SSL_set_read_ahead(SSL *s, int yes)
802 {
803 	s->internal->read_ahead = yes;
804 }
805 
806 int
807 SSL_get_read_ahead(const SSL *s)
808 {
809 	return (s->internal->read_ahead);
810 }
811 
812 int
813 SSL_pending(const SSL *s)
814 {
815 	return (s->method->internal->ssl_pending(s));
816 }
817 
818 X509 *
819 SSL_get_peer_certificate(const SSL *s)
820 {
821 	X509	*r;
822 
823 	if ((s == NULL) || (s->session == NULL))
824 		r = NULL;
825 	else
826 		r = s->session->peer;
827 
828 	if (r == NULL)
829 		return (r);
830 
831 	CRYPTO_add(&r->references, 1, CRYPTO_LOCK_X509);
832 
833 	return (r);
834 }
835 
836 STACK_OF(X509) *
837 SSL_get_peer_cert_chain(const SSL *s)
838 {
839 	STACK_OF(X509)	*r;
840 
841 	if ((s == NULL) || (s->session == NULL) ||
842 	    (SSI(s)->sess_cert == NULL))
843 		r = NULL;
844 	else
845 		r = SSI(s)->sess_cert->cert_chain;
846 
847 	/*
848 	 * If we are a client, cert_chain includes the peer's own
849 	 * certificate;
850 	 * if we are a server, it does not.
851 	 */
852 	return (r);
853 }
854 
855 /*
856  * Now in theory, since the calling process own 't' it should be safe to
857  * modify.  We need to be able to read f without being hassled
858  */
859 int
860 SSL_copy_session_id(SSL *t, const SSL *f)
861 {
862 	CERT	*tmp;
863 
864 	/* Do we need to do SSL locking? */
865 	if (!SSL_set_session(t, SSL_get_session(f)))
866 		return 0;
867 
868 	/* What if we are set up for one protocol but want to talk another? */
869 	if (t->method != f->method) {
870 		t->method->internal->ssl_free(t);
871 		t->method = f->method;
872 		if (!t->method->internal->ssl_new(t))
873 			return 0;
874 	}
875 
876 	tmp = t->cert;
877 	if (f->cert != NULL) {
878 		CRYPTO_add(&f->cert->references, 1, CRYPTO_LOCK_SSL_CERT);
879 		t->cert = f->cert;
880 	} else
881 		t->cert = NULL;
882 	ssl_cert_free(tmp);
883 
884 	if (!SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length))
885 		return 0;
886 
887 	return 1;
888 }
889 
890 /* Fix this so it checks all the valid key/cert options */
891 int
892 SSL_CTX_check_private_key(const SSL_CTX *ctx)
893 {
894 	if ((ctx == NULL) || (ctx->internal->cert == NULL) ||
895 	    (ctx->internal->cert->key->x509 == NULL)) {
896 		SSLerrorx(SSL_R_NO_CERTIFICATE_ASSIGNED);
897 		return (0);
898 	}
899 	if (ctx->internal->cert->key->privatekey == NULL) {
900 		SSLerrorx(SSL_R_NO_PRIVATE_KEY_ASSIGNED);
901 		return (0);
902 	}
903 	return (X509_check_private_key(ctx->internal->cert->key->x509,
904 	    ctx->internal->cert->key->privatekey));
905 }
906 
907 /* Fix this function so that it takes an optional type parameter */
908 int
909 SSL_check_private_key(const SSL *ssl)
910 {
911 	if (ssl == NULL) {
912 		SSLerrorx(ERR_R_PASSED_NULL_PARAMETER);
913 		return (0);
914 	}
915 	if (ssl->cert == NULL) {
916 		SSLerror(ssl, SSL_R_NO_CERTIFICATE_ASSIGNED);
917 		return (0);
918 	}
919 	if (ssl->cert->key->x509 == NULL) {
920 		SSLerror(ssl, SSL_R_NO_CERTIFICATE_ASSIGNED);
921 		return (0);
922 	}
923 	if (ssl->cert->key->privatekey == NULL) {
924 		SSLerror(ssl, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
925 		return (0);
926 	}
927 	return (X509_check_private_key(ssl->cert->key->x509,
928 	    ssl->cert->key->privatekey));
929 }
930 
931 int
932 SSL_accept(SSL *s)
933 {
934 	if (s->internal->handshake_func == NULL)
935 		SSL_set_accept_state(s); /* Not properly initialized yet */
936 
937 	return (s->method->internal->ssl_accept(s));
938 }
939 
940 int
941 SSL_connect(SSL *s)
942 {
943 	if (s->internal->handshake_func == NULL)
944 		SSL_set_connect_state(s); /* Not properly initialized yet */
945 
946 	return (s->method->internal->ssl_connect(s));
947 }
948 
949 int
950 SSL_is_dtls(const SSL *s)
951 {
952 	return s->method->internal->dtls;
953 }
954 
955 int
956 SSL_is_server(const SSL *s)
957 {
958 	return s->server;
959 }
960 
961 static long
962 ssl_get_default_timeout()
963 {
964 	/*
965 	 * 2 hours, the 24 hours mentioned in the TLSv1 spec
966 	 * is way too long for http, the cache would over fill.
967 	 */
968 	return (2 * 60 * 60);
969 }
970 
971 long
972 SSL_get_default_timeout(const SSL *s)
973 {
974 	return (ssl_get_default_timeout());
975 }
976 
977 int
978 SSL_read(SSL *s, void *buf, int num)
979 {
980 	if (s->internal->handshake_func == NULL) {
981 		SSLerror(s, SSL_R_UNINITIALIZED);
982 		return (-1);
983 	}
984 
985 	if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
986 		s->internal->rwstate = SSL_NOTHING;
987 		return (0);
988 	}
989 	return ssl3_read(s, buf, num);
990 }
991 
992 int
993 SSL_peek(SSL *s, void *buf, int num)
994 {
995 	if (s->internal->handshake_func == NULL) {
996 		SSLerror(s, SSL_R_UNINITIALIZED);
997 		return (-1);
998 	}
999 
1000 	if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
1001 		return (0);
1002 	}
1003 	return ssl3_peek(s, buf, num);
1004 }
1005 
1006 int
1007 SSL_write(SSL *s, const void *buf, int num)
1008 {
1009 	if (s->internal->handshake_func == NULL) {
1010 		SSLerror(s, SSL_R_UNINITIALIZED);
1011 		return (-1);
1012 	}
1013 
1014 	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) {
1015 		s->internal->rwstate = SSL_NOTHING;
1016 		SSLerror(s, SSL_R_PROTOCOL_IS_SHUTDOWN);
1017 		return (-1);
1018 	}
1019 	return ssl3_write(s, buf, num);
1020 }
1021 
1022 uint32_t
1023 SSL_CTX_get_max_early_data(const SSL_CTX *ctx)
1024 {
1025 	return 0;
1026 }
1027 
1028 int
1029 SSL_CTX_set_max_early_data(SSL_CTX *ctx, uint32_t max_early_data)
1030 {
1031 	return 1;
1032 }
1033 
1034 uint32_t
1035 SSL_get_max_early_data(const SSL *s)
1036 {
1037 	return 0;
1038 }
1039 
1040 int
1041 SSL_set_max_early_data(SSL *s, uint32_t max_early_data)
1042 {
1043 	return 1;
1044 }
1045 
1046 int
1047 SSL_get_early_data_status(const SSL *s)
1048 {
1049 	return SSL_EARLY_DATA_REJECTED;
1050 }
1051 
1052 int
1053 SSL_read_early_data(SSL *s, void *buf, size_t num, size_t *readbytes)
1054 {
1055 	*readbytes = 0;
1056 
1057 	if (!s->server) {
1058 		SSLerror(s, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1059 		return SSL_READ_EARLY_DATA_ERROR;
1060 	}
1061 
1062 	return SSL_READ_EARLY_DATA_FINISH;
1063 }
1064 
1065 int
1066 SSL_write_early_data(SSL *s, const void *buf, size_t num, size_t *written)
1067 {
1068 	*written = 0;
1069 	SSLerror(s, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1070 	return 0;
1071 }
1072 
1073 int
1074 SSL_shutdown(SSL *s)
1075 {
1076 	/*
1077 	 * Note that this function behaves differently from what one might
1078 	 * expect.  Return values are 0 for no success (yet),
1079 	 * 1 for success; but calling it once is usually not enough,
1080 	 * even if blocking I/O is used (see ssl3_shutdown).
1081 	 */
1082 
1083 	if (s->internal->handshake_func == NULL) {
1084 		SSLerror(s, SSL_R_UNINITIALIZED);
1085 		return (-1);
1086 	}
1087 
1088 	if (s != NULL && !SSL_in_init(s))
1089 		return (s->method->internal->ssl_shutdown(s));
1090 
1091 	return (1);
1092 }
1093 
1094 int
1095 SSL_renegotiate(SSL *s)
1096 {
1097 	if (s->internal->renegotiate == 0)
1098 		s->internal->renegotiate = 1;
1099 
1100 	s->internal->new_session = 1;
1101 
1102 	return (s->method->internal->ssl_renegotiate(s));
1103 }
1104 
1105 int
1106 SSL_renegotiate_abbreviated(SSL *s)
1107 {
1108 	if (s->internal->renegotiate == 0)
1109 		s->internal->renegotiate = 1;
1110 
1111 	s->internal->new_session = 0;
1112 
1113 	return (s->method->internal->ssl_renegotiate(s));
1114 }
1115 
1116 int
1117 SSL_renegotiate_pending(SSL *s)
1118 {
1119 	/*
1120 	 * Becomes true when negotiation is requested;
1121 	 * false again once a handshake has finished.
1122 	 */
1123 	return (s->internal->renegotiate != 0);
1124 }
1125 
1126 long
1127 SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
1128 {
1129 	long	l;
1130 
1131 	switch (cmd) {
1132 	case SSL_CTRL_GET_READ_AHEAD:
1133 		return (s->internal->read_ahead);
1134 	case SSL_CTRL_SET_READ_AHEAD:
1135 		l = s->internal->read_ahead;
1136 		s->internal->read_ahead = larg;
1137 		return (l);
1138 
1139 	case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1140 		s->internal->msg_callback_arg = parg;
1141 		return (1);
1142 
1143 	case SSL_CTRL_OPTIONS:
1144 		return (s->internal->options|=larg);
1145 	case SSL_CTRL_CLEAR_OPTIONS:
1146 		return (s->internal->options&=~larg);
1147 	case SSL_CTRL_MODE:
1148 		return (s->internal->mode|=larg);
1149 	case SSL_CTRL_CLEAR_MODE:
1150 		return (s->internal->mode &=~larg);
1151 	case SSL_CTRL_GET_MAX_CERT_LIST:
1152 		return (s->internal->max_cert_list);
1153 	case SSL_CTRL_SET_MAX_CERT_LIST:
1154 		l = s->internal->max_cert_list;
1155 		s->internal->max_cert_list = larg;
1156 		return (l);
1157 	case SSL_CTRL_SET_MTU:
1158 #ifndef OPENSSL_NO_DTLS1
1159 		if (larg < (long)dtls1_min_mtu())
1160 			return (0);
1161 #endif
1162 		if (SSL_is_dtls(s)) {
1163 			D1I(s)->mtu = larg;
1164 			return (larg);
1165 		}
1166 		return (0);
1167 	case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1168 		if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1169 			return (0);
1170 		s->max_send_fragment = larg;
1171 		return (1);
1172 	case SSL_CTRL_GET_RI_SUPPORT:
1173 		if (s->s3)
1174 			return (S3I(s)->send_connection_binding);
1175 		else return (0);
1176 	default:
1177 		if (SSL_is_dtls(s))
1178 			return dtls1_ctrl(s, cmd, larg, parg);
1179 		return ssl3_ctrl(s, cmd, larg, parg);
1180 	}
1181 }
1182 
1183 long
1184 SSL_callback_ctrl(SSL *s, int cmd, void (*fp)(void))
1185 {
1186 	switch (cmd) {
1187 	case SSL_CTRL_SET_MSG_CALLBACK:
1188 		s->internal->msg_callback = (void (*)(int write_p, int version,
1189 		    int content_type, const void *buf, size_t len,
1190 		    SSL *ssl, void *arg))(fp);
1191 		return (1);
1192 
1193 	default:
1194 		return (ssl3_callback_ctrl(s, cmd, fp));
1195 	}
1196 }
1197 
1198 struct lhash_st_SSL_SESSION *
1199 SSL_CTX_sessions(SSL_CTX *ctx)
1200 {
1201 	return (ctx->internal->sessions);
1202 }
1203 
1204 long
1205 SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
1206 {
1207 	long	l;
1208 
1209 	switch (cmd) {
1210 	case SSL_CTRL_GET_READ_AHEAD:
1211 		return (ctx->internal->read_ahead);
1212 	case SSL_CTRL_SET_READ_AHEAD:
1213 		l = ctx->internal->read_ahead;
1214 		ctx->internal->read_ahead = larg;
1215 		return (l);
1216 
1217 	case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1218 		ctx->internal->msg_callback_arg = parg;
1219 		return (1);
1220 
1221 	case SSL_CTRL_GET_MAX_CERT_LIST:
1222 		return (ctx->internal->max_cert_list);
1223 	case SSL_CTRL_SET_MAX_CERT_LIST:
1224 		l = ctx->internal->max_cert_list;
1225 		ctx->internal->max_cert_list = larg;
1226 		return (l);
1227 
1228 	case SSL_CTRL_SET_SESS_CACHE_SIZE:
1229 		l = ctx->internal->session_cache_size;
1230 		ctx->internal->session_cache_size = larg;
1231 		return (l);
1232 	case SSL_CTRL_GET_SESS_CACHE_SIZE:
1233 		return (ctx->internal->session_cache_size);
1234 	case SSL_CTRL_SET_SESS_CACHE_MODE:
1235 		l = ctx->internal->session_cache_mode;
1236 		ctx->internal->session_cache_mode = larg;
1237 		return (l);
1238 	case SSL_CTRL_GET_SESS_CACHE_MODE:
1239 		return (ctx->internal->session_cache_mode);
1240 
1241 	case SSL_CTRL_SESS_NUMBER:
1242 		return (lh_SSL_SESSION_num_items(ctx->internal->sessions));
1243 	case SSL_CTRL_SESS_CONNECT:
1244 		return (ctx->internal->stats.sess_connect);
1245 	case SSL_CTRL_SESS_CONNECT_GOOD:
1246 		return (ctx->internal->stats.sess_connect_good);
1247 	case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
1248 		return (ctx->internal->stats.sess_connect_renegotiate);
1249 	case SSL_CTRL_SESS_ACCEPT:
1250 		return (ctx->internal->stats.sess_accept);
1251 	case SSL_CTRL_SESS_ACCEPT_GOOD:
1252 		return (ctx->internal->stats.sess_accept_good);
1253 	case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
1254 		return (ctx->internal->stats.sess_accept_renegotiate);
1255 	case SSL_CTRL_SESS_HIT:
1256 		return (ctx->internal->stats.sess_hit);
1257 	case SSL_CTRL_SESS_CB_HIT:
1258 		return (ctx->internal->stats.sess_cb_hit);
1259 	case SSL_CTRL_SESS_MISSES:
1260 		return (ctx->internal->stats.sess_miss);
1261 	case SSL_CTRL_SESS_TIMEOUTS:
1262 		return (ctx->internal->stats.sess_timeout);
1263 	case SSL_CTRL_SESS_CACHE_FULL:
1264 		return (ctx->internal->stats.sess_cache_full);
1265 	case SSL_CTRL_OPTIONS:
1266 		return (ctx->internal->options|=larg);
1267 	case SSL_CTRL_CLEAR_OPTIONS:
1268 		return (ctx->internal->options&=~larg);
1269 	case SSL_CTRL_MODE:
1270 		return (ctx->internal->mode|=larg);
1271 	case SSL_CTRL_CLEAR_MODE:
1272 		return (ctx->internal->mode&=~larg);
1273 	case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1274 		if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1275 			return (0);
1276 		ctx->internal->max_send_fragment = larg;
1277 		return (1);
1278 	default:
1279 		return (ssl3_ctx_ctrl(ctx, cmd, larg, parg));
1280 	}
1281 }
1282 
1283 long
1284 SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp)(void))
1285 {
1286 	switch (cmd) {
1287 	case SSL_CTRL_SET_MSG_CALLBACK:
1288 		ctx->internal->msg_callback = (void (*)(int write_p, int version,
1289 		    int content_type, const void *buf, size_t len, SSL *ssl,
1290 		    void *arg))(fp);
1291 		return (1);
1292 
1293 	default:
1294 		return (ssl3_ctx_callback_ctrl(ctx, cmd, fp));
1295 	}
1296 }
1297 
1298 int
1299 ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
1300 {
1301 	long	l;
1302 
1303 	l = a->id - b->id;
1304 	if (l == 0L)
1305 		return (0);
1306 	else
1307 		return ((l > 0) ? 1:-1);
1308 }
1309 
1310 STACK_OF(SSL_CIPHER) *
1311 SSL_get_ciphers(const SSL *s)
1312 {
1313 	if (s == NULL)
1314 		return (NULL);
1315 	if (s->cipher_list != NULL)
1316 		return (s->cipher_list);
1317 
1318 	return (s->ctx->cipher_list);
1319 }
1320 
1321 STACK_OF(SSL_CIPHER) *
1322 SSL_get_client_ciphers(const SSL *s)
1323 {
1324 	if (s == NULL || s->session == NULL || !s->server)
1325 		return NULL;
1326 	return s->session->ciphers;
1327 }
1328 
1329 STACK_OF(SSL_CIPHER) *
1330 SSL_get1_supported_ciphers(SSL *s)
1331 {
1332 	STACK_OF(SSL_CIPHER) *supported_ciphers = NULL, *ciphers;
1333 	const SSL_CIPHER *cipher;
1334 	uint16_t min_vers, max_vers;
1335 	int i;
1336 
1337 	if (s == NULL)
1338 		return NULL;
1339 	if (!ssl_supported_tls_version_range(s, &min_vers, &max_vers))
1340 		return NULL;
1341 	if ((ciphers = SSL_get_ciphers(s)) == NULL)
1342 		return NULL;
1343 	if ((supported_ciphers = sk_SSL_CIPHER_new_null()) == NULL)
1344 		return NULL;
1345 
1346 	for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1347 		if ((cipher = sk_SSL_CIPHER_value(ciphers, i)) == NULL)
1348 			goto err;
1349 		if (!ssl_cipher_allowed_in_tls_version_range(cipher, min_vers,
1350 		    max_vers))
1351 			continue;
1352 		if (!sk_SSL_CIPHER_push(supported_ciphers, cipher))
1353 			goto err;
1354 	}
1355 
1356 	if (sk_SSL_CIPHER_num(supported_ciphers) > 0)
1357 		return supported_ciphers;
1358 
1359  err:
1360 	sk_SSL_CIPHER_free(supported_ciphers);
1361 	return NULL;
1362 }
1363 
1364 /* See if we have any ECC cipher suites. */
1365 int
1366 ssl_has_ecc_ciphers(SSL *s)
1367 {
1368 	STACK_OF(SSL_CIPHER) *ciphers;
1369 	unsigned long alg_k, alg_a;
1370 	SSL_CIPHER *cipher;
1371 	int i;
1372 
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(). */
1390 const char *
1391 SSL_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 
1404 STACK_OF(SSL_CIPHER) *
1405 SSL_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. */
1413 int
1414 SSL_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 
1436 int
1437 SSL_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. */
1451 int
1452 SSL_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 
1471 int
1472 SSL_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 
1490 char *
1491 SSL_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  */
1535 const char *
1536 SSL_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 
1546 int
1547 SSL_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  */
1569 int
1570 SSL_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 
1603  found:
1604 	*out = (unsigned char *) result + 1;
1605 	*outlen = result[0];
1606 	return (status);
1607 }
1608 
1609 /* SSL_get0_next_proto_negotiated is deprecated. */
1610 void
1611 SSL_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. */
1619 void
1620 SSL_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. */
1626 void
1627 SSL_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  */
1638 int
1639 SSL_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  */
1670 int
1671 SSL_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  */
1702 void
1703 SSL_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  */
1717 void
1718 SSL_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 
1728 int
1729 SSL_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 
1746 static unsigned long
1747 ssl_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  */
1766 static int
1767 ssl_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  */
1784 static unsigned long
1785 ssl_session_LHASH_HASH(const void *arg)
1786 {
1787 	const SSL_SESSION *a = arg;
1788 
1789 	return ssl_session_hash(a);
1790 }
1791 
1792 static int
1793 ssl_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 
1801 SSL_CTX *
1802 SSL_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_tls_version = meth->internal->min_tls_version;
1833 	ret->internal->max_tls_version = meth->internal->max_tls_version;
1834 	ret->internal->min_proto_version = 0;
1835 	ret->internal->max_proto_version = 0;
1836 	ret->internal->mode = SSL_MODE_AUTO_RETRY;
1837 
1838 	ret->cert_store = NULL;
1839 	ret->internal->session_cache_mode = SSL_SESS_CACHE_SERVER;
1840 	ret->internal->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
1841 	ret->internal->session_cache_head = NULL;
1842 	ret->internal->session_cache_tail = NULL;
1843 
1844 	/* We take the system default */
1845 	ret->session_timeout = ssl_get_default_timeout();
1846 
1847 	ret->internal->new_session_cb = 0;
1848 	ret->internal->remove_session_cb = 0;
1849 	ret->internal->get_session_cb = 0;
1850 	ret->internal->generate_session_id = 0;
1851 
1852 	memset((char *)&ret->internal->stats, 0, sizeof(ret->internal->stats));
1853 
1854 	ret->references = 1;
1855 	ret->internal->quiet_shutdown = 0;
1856 
1857 	ret->internal->info_callback = NULL;
1858 
1859 	ret->internal->app_verify_callback = 0;
1860 	ret->internal->app_verify_arg = NULL;
1861 
1862 	ret->internal->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
1863 	ret->internal->read_ahead = 0;
1864 	ret->internal->msg_callback = 0;
1865 	ret->internal->msg_callback_arg = NULL;
1866 	ret->verify_mode = SSL_VERIFY_NONE;
1867 	ret->sid_ctx_length = 0;
1868 	ret->internal->default_verify_callback = NULL;
1869 
1870 	if ((ret->internal->cert = ssl_cert_new()) == NULL)
1871 		goto err;
1872 
1873 	ret->default_passwd_callback = 0;
1874 	ret->default_passwd_callback_userdata = NULL;
1875 	ret->internal->client_cert_cb = 0;
1876 	ret->internal->app_gen_cookie_cb = 0;
1877 	ret->internal->app_verify_cookie_cb = 0;
1878 
1879 	ret->internal->sessions = lh_SSL_SESSION_new();
1880 	if (ret->internal->sessions == NULL)
1881 		goto err;
1882 	ret->cert_store = X509_STORE_new();
1883 	if (ret->cert_store == NULL)
1884 		goto err;
1885 
1886 	ssl_create_cipher_list(ret->method, &ret->cipher_list,
1887 	    NULL, SSL_DEFAULT_CIPHER_LIST);
1888 	if (ret->cipher_list == NULL ||
1889 	    sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
1890 		SSLerrorx(SSL_R_LIBRARY_HAS_NO_CIPHERS);
1891 		goto err2;
1892 	}
1893 
1894 	ret->param = X509_VERIFY_PARAM_new();
1895 	if (!ret->param)
1896 		goto err;
1897 
1898 	if ((ret->internal->client_CA = sk_X509_NAME_new_null()) == NULL)
1899 		goto err;
1900 
1901 	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->internal->ex_data);
1902 
1903 	ret->extra_certs = NULL;
1904 
1905 	ret->internal->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1906 
1907 	ret->internal->tlsext_servername_callback = 0;
1908 	ret->internal->tlsext_servername_arg = NULL;
1909 
1910 	/* Setup RFC4507 ticket keys */
1911 	arc4random_buf(ret->internal->tlsext_tick_key_name, 16);
1912 	arc4random_buf(ret->internal->tlsext_tick_hmac_key, 16);
1913 	arc4random_buf(ret->internal->tlsext_tick_aes_key, 16);
1914 
1915 	ret->internal->tlsext_status_cb = 0;
1916 	ret->internal->tlsext_status_arg = NULL;
1917 
1918 #ifndef OPENSSL_NO_ENGINE
1919 	ret->internal->client_cert_engine = NULL;
1920 #ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
1921 #define eng_strx(x)	#x
1922 #define eng_str(x)	eng_strx(x)
1923 	/* Use specific client engine automatically... ignore errors */
1924 	{
1925 		ENGINE *eng;
1926 		eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1927 		if (!eng) {
1928 			ERR_clear_error();
1929 			ENGINE_load_builtin_engines();
1930 			eng = ENGINE_by_id(eng_str(
1931 			    OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1932 		}
1933 		if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
1934 			ERR_clear_error();
1935 	}
1936 #endif
1937 #endif
1938 	/*
1939 	 * Default is to connect to non-RI servers. When RI is more widely
1940 	 * deployed might change this.
1941 	 */
1942 	ret->internal->options |= SSL_OP_LEGACY_SERVER_CONNECT;
1943 
1944 	return (ret);
1945  err:
1946 	SSLerrorx(ERR_R_MALLOC_FAILURE);
1947  err2:
1948 	SSL_CTX_free(ret);
1949 	return (NULL);
1950 }
1951 
1952 void
1953 SSL_CTX_free(SSL_CTX *ctx)
1954 {
1955 	int	i;
1956 
1957 	if (ctx == NULL)
1958 		return;
1959 
1960 	i = CRYPTO_add(&ctx->references, -1, CRYPTO_LOCK_SSL_CTX);
1961 	if (i > 0)
1962 		return;
1963 
1964 	X509_VERIFY_PARAM_free(ctx->param);
1965 
1966 	/*
1967 	 * Free internal session cache. However: the remove_cb() may reference
1968 	 * the ex_data of SSL_CTX, thus the ex_data store can only be removed
1969 	 * after the sessions were flushed.
1970 	 * As the ex_data handling routines might also touch the session cache,
1971 	 * the most secure solution seems to be: empty (flush) the cache, then
1972 	 * free ex_data, then finally free the cache.
1973 	 * (See ticket [openssl.org #212].)
1974 	 */
1975 	if (ctx->internal->sessions != NULL)
1976 		SSL_CTX_flush_sessions(ctx, 0);
1977 
1978 	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ctx, &ctx->internal->ex_data);
1979 
1980 	lh_SSL_SESSION_free(ctx->internal->sessions);
1981 
1982 	X509_STORE_free(ctx->cert_store);
1983 	sk_SSL_CIPHER_free(ctx->cipher_list);
1984 	sk_SSL_CIPHER_free(ctx->internal->cipher_list_tls13);
1985 	ssl_cert_free(ctx->internal->cert);
1986 	sk_X509_NAME_pop_free(ctx->internal->client_CA, X509_NAME_free);
1987 	sk_X509_pop_free(ctx->extra_certs, X509_free);
1988 
1989 #ifndef OPENSSL_NO_SRTP
1990 	if (ctx->internal->srtp_profiles)
1991 		sk_SRTP_PROTECTION_PROFILE_free(ctx->internal->srtp_profiles);
1992 #endif
1993 
1994 #ifndef OPENSSL_NO_ENGINE
1995 	ENGINE_finish(ctx->internal->client_cert_engine);
1996 #endif
1997 
1998 	free(ctx->internal->tlsext_ecpointformatlist);
1999 	free(ctx->internal->tlsext_supportedgroups);
2000 
2001 	free(ctx->internal->alpn_client_proto_list);
2002 
2003 	free(ctx->internal);
2004 	free(ctx);
2005 }
2006 
2007 int
2008 SSL_CTX_up_ref(SSL_CTX *ctx)
2009 {
2010 	int refs = CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
2011 	return ((refs > 1) ? 1 : 0);
2012 }
2013 
2014 pem_password_cb *
2015 SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
2016 {
2017 	return (ctx->default_passwd_callback);
2018 }
2019 
2020 void
2021 SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2022 {
2023 	ctx->default_passwd_callback = cb;
2024 }
2025 
2026 void *
2027 SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
2028 {
2029 	return ctx->default_passwd_callback_userdata;
2030 }
2031 
2032 void
2033 SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2034 {
2035 	ctx->default_passwd_callback_userdata = u;
2036 }
2037 
2038 void
2039 SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
2040     int (*cb)(X509_STORE_CTX *, void *), void *arg)
2041 {
2042 	ctx->internal->app_verify_callback = cb;
2043 	ctx->internal->app_verify_arg = arg;
2044 }
2045 
2046 void
2047 SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*cb)(int, X509_STORE_CTX *))
2048 {
2049 	ctx->verify_mode = mode;
2050 	ctx->internal->default_verify_callback = cb;
2051 }
2052 
2053 void
2054 SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
2055 {
2056 	X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2057 }
2058 
2059 static int
2060 ssl_cert_can_sign(X509 *x)
2061 {
2062 	/* This call populates extension flags (ex_flags). */
2063 	X509_check_purpose(x, -1, 0);
2064 
2065 	/* Key usage, if present, must allow signing. */
2066 	return ((x->ex_flags & EXFLAG_KUSAGE) == 0 ||
2067 	    (x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE));
2068 }
2069 
2070 void
2071 ssl_set_cert_masks(CERT *c, const SSL_CIPHER *cipher)
2072 {
2073 	unsigned long mask_a, mask_k;
2074 	CERT_PKEY *cpk;
2075 
2076 	if (c == NULL)
2077 		return;
2078 
2079 	mask_a = SSL_aNULL | SSL_aTLS1_3;
2080 	mask_k = SSL_kECDHE | SSL_kTLS1_3;
2081 
2082 	if (c->dh_tmp != NULL || c->dh_tmp_cb != NULL || c->dh_tmp_auto != 0)
2083 		mask_k |= SSL_kDHE;
2084 
2085 	cpk = &(c->pkeys[SSL_PKEY_ECC]);
2086 	if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2087 		if (ssl_cert_can_sign(cpk->x509))
2088 			mask_a |= SSL_aECDSA;
2089 	}
2090 
2091 	cpk = &(c->pkeys[SSL_PKEY_GOST01]);
2092 	if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2093 		mask_k |= SSL_kGOST;
2094 		mask_a |= SSL_aGOST01;
2095 	}
2096 
2097 	cpk = &(c->pkeys[SSL_PKEY_RSA]);
2098 	if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2099 		mask_a |= SSL_aRSA;
2100 		mask_k |= SSL_kRSA;
2101 	}
2102 
2103 	c->mask_k = mask_k;
2104 	c->mask_a = mask_a;
2105 	c->valid = 1;
2106 }
2107 
2108 /* See if this handshake is using an ECC cipher suite. */
2109 int
2110 ssl_using_ecc_cipher(SSL *s)
2111 {
2112 	unsigned long alg_a, alg_k;
2113 
2114 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
2115 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2116 
2117 	return SSI(s)->tlsext_ecpointformatlist != NULL &&
2118 	    SSI(s)->tlsext_ecpointformatlist_length > 0 &&
2119 	    ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA));
2120 }
2121 
2122 int
2123 ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
2124 {
2125 	const SSL_CIPHER	*cs = S3I(s)->hs.new_cipher;
2126 	unsigned long		 alg_a;
2127 
2128 	alg_a = cs->algorithm_auth;
2129 
2130 	if (alg_a & SSL_aECDSA) {
2131 		/* This call populates extension flags (ex_flags). */
2132 		X509_check_purpose(x, -1, 0);
2133 
2134 		/* Key usage, if present, must allow signing. */
2135 		if ((x->ex_flags & EXFLAG_KUSAGE) &&
2136 		    ((x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE) == 0)) {
2137 			SSLerror(s, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2138 			return (0);
2139 		}
2140 	}
2141 
2142 	return (1);
2143 }
2144 
2145 CERT_PKEY *
2146 ssl_get_server_send_pkey(const SSL *s)
2147 {
2148 	unsigned long	 alg_a;
2149 	CERT		*c;
2150 	int		 i;
2151 
2152 	c = s->cert;
2153 	ssl_set_cert_masks(c, S3I(s)->hs.new_cipher);
2154 
2155 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
2156 
2157 	if (alg_a & SSL_aECDSA) {
2158 		i = SSL_PKEY_ECC;
2159 	} else if (alg_a & SSL_aRSA) {
2160 		i = SSL_PKEY_RSA;
2161 	} else if (alg_a & SSL_aGOST01) {
2162 		i = SSL_PKEY_GOST01;
2163 	} else { /* if (alg_a & SSL_aNULL) */
2164 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2165 		return (NULL);
2166 	}
2167 
2168 	return (c->pkeys + i);
2169 }
2170 
2171 EVP_PKEY *
2172 ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher, const EVP_MD **pmd,
2173     const struct ssl_sigalg **sap)
2174 {
2175 	const struct ssl_sigalg *sigalg = NULL;
2176 	EVP_PKEY *pkey = NULL;
2177 	unsigned long	 alg_a;
2178 	CERT		*c;
2179 	int		 idx = -1;
2180 
2181 	alg_a = cipher->algorithm_auth;
2182 	c = s->cert;
2183 
2184 	if (alg_a & SSL_aRSA) {
2185 		idx = SSL_PKEY_RSA;
2186 	} else if ((alg_a & SSL_aECDSA) &&
2187 	    (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2188 		idx = SSL_PKEY_ECC;
2189 	if (idx == -1) {
2190 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2191 		return (NULL);
2192 	}
2193 
2194 	pkey = c->pkeys[idx].privatekey;
2195 	if ((sigalg = ssl_sigalg_select(s, pkey)) == NULL) {
2196 		SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2197 		return (NULL);
2198 	}
2199 	*pmd = sigalg->md();
2200 	*sap = sigalg;
2201 
2202 	return (pkey);
2203 }
2204 
2205 DH *
2206 ssl_get_auto_dh(SSL *s)
2207 {
2208 	CERT_PKEY *cpk;
2209 	int keylen;
2210 	DH *dhp;
2211 
2212 	if (s->cert->dh_tmp_auto == 2) {
2213 		keylen = 1024;
2214 	} else if (S3I(s)->hs.new_cipher->algorithm_auth & SSL_aNULL) {
2215 		keylen = 1024;
2216 		if (S3I(s)->hs.new_cipher->strength_bits == 256)
2217 			keylen = 3072;
2218 	} else {
2219 		if ((cpk = ssl_get_server_send_pkey(s)) == NULL)
2220 			return (NULL);
2221 		if (cpk->privatekey == NULL || cpk->privatekey->pkey.dh == NULL)
2222 			return (NULL);
2223 		keylen = EVP_PKEY_bits(cpk->privatekey);
2224 	}
2225 
2226 	if ((dhp = DH_new()) == NULL)
2227 		return (NULL);
2228 
2229 	dhp->g = BN_new();
2230 	if (dhp->g != NULL)
2231 		BN_set_word(dhp->g, 2);
2232 
2233 	if (keylen >= 8192)
2234 		dhp->p = get_rfc3526_prime_8192(NULL);
2235 	else if (keylen >= 4096)
2236 		dhp->p = get_rfc3526_prime_4096(NULL);
2237 	else if (keylen >= 3072)
2238 		dhp->p = get_rfc3526_prime_3072(NULL);
2239 	else if (keylen >= 2048)
2240 		dhp->p = get_rfc3526_prime_2048(NULL);
2241 	else if (keylen >= 1536)
2242 		dhp->p = get_rfc3526_prime_1536(NULL);
2243 	else
2244 		dhp->p = get_rfc2409_prime_1024(NULL);
2245 
2246 	if (dhp->p == NULL || dhp->g == NULL) {
2247 		DH_free(dhp);
2248 		return (NULL);
2249 	}
2250 	return (dhp);
2251 }
2252 
2253 void
2254 ssl_update_cache(SSL *s, int mode)
2255 {
2256 	int	i;
2257 
2258 	/*
2259 	 * If the session_id_length is 0, we are not supposed to cache it,
2260 	 * and it would be rather hard to do anyway :-)
2261 	 */
2262 	if (s->session->session_id_length == 0)
2263 		return;
2264 
2265 	i = s->session_ctx->internal->session_cache_mode;
2266 	if ((i & mode) && (!s->internal->hit) && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
2267 	    || SSL_CTX_add_session(s->session_ctx, s->session))
2268 	    && (s->session_ctx->internal->new_session_cb != NULL)) {
2269 		CRYPTO_add(&s->session->references, 1, CRYPTO_LOCK_SSL_SESSION);
2270 		if (!s->session_ctx->internal->new_session_cb(s, s->session))
2271 			SSL_SESSION_free(s->session);
2272 	}
2273 
2274 	/* auto flush every 255 connections */
2275 	if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) &&
2276 	    ((i & mode) == mode)) {
2277 		if ((((mode & SSL_SESS_CACHE_CLIENT) ?
2278 		    s->session_ctx->internal->stats.sess_connect_good :
2279 		    s->session_ctx->internal->stats.sess_accept_good) & 0xff) == 0xff) {
2280 			SSL_CTX_flush_sessions(s->session_ctx, time(NULL));
2281 		}
2282 	}
2283 }
2284 
2285 const SSL_METHOD *
2286 SSL_get_ssl_method(SSL *s)
2287 {
2288 	return (s->method);
2289 }
2290 
2291 int
2292 SSL_set_ssl_method(SSL *s, const SSL_METHOD *method)
2293 {
2294 	int (*handshake_func)(SSL *) = NULL;
2295 	int ret = 1;
2296 
2297 	if (s->method == method)
2298 		return (ret);
2299 
2300 	if (s->internal->handshake_func == s->method->internal->ssl_connect)
2301 		handshake_func = method->internal->ssl_connect;
2302 	else if (s->internal->handshake_func == s->method->internal->ssl_accept)
2303 		handshake_func = method->internal->ssl_accept;
2304 
2305 	if (s->method->internal->version == method->internal->version) {
2306 		s->method = method;
2307 	} else {
2308 		s->method->internal->ssl_free(s);
2309 		s->method = method;
2310 		ret = s->method->internal->ssl_new(s);
2311 	}
2312 	s->internal->handshake_func = handshake_func;
2313 
2314 	return (ret);
2315 }
2316 
2317 int
2318 SSL_get_error(const SSL *s, int i)
2319 {
2320 	int		 reason;
2321 	unsigned long	 l;
2322 	BIO		*bio;
2323 
2324 	if (i > 0)
2325 		return (SSL_ERROR_NONE);
2326 
2327 	/* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake
2328 	 * etc, where we do encode the error */
2329 	if ((l = ERR_peek_error()) != 0) {
2330 		if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2331 			return (SSL_ERROR_SYSCALL);
2332 		else
2333 			return (SSL_ERROR_SSL);
2334 	}
2335 
2336 	if ((i < 0) && SSL_want_read(s)) {
2337 		bio = SSL_get_rbio(s);
2338 		if (BIO_should_read(bio)) {
2339 			return (SSL_ERROR_WANT_READ);
2340 		} else if (BIO_should_write(bio)) {
2341 			/*
2342 			 * This one doesn't make too much sense...  We never
2343 			 * try to write to the rbio, and an application
2344 			 * program where rbio and wbio are separate couldn't
2345 			 * even know what it should wait for.  However if we
2346 			 * ever set s->internal->rwstate incorrectly (so that we have
2347 			 * SSL_want_read(s) instead of SSL_want_write(s))
2348 			 * and rbio and wbio *are* the same, this test works
2349 			 * around that bug; so it might be safer to keep it.
2350 			 */
2351 			return (SSL_ERROR_WANT_WRITE);
2352 		} else if (BIO_should_io_special(bio)) {
2353 			reason = BIO_get_retry_reason(bio);
2354 			if (reason == BIO_RR_CONNECT)
2355 				return (SSL_ERROR_WANT_CONNECT);
2356 			else if (reason == BIO_RR_ACCEPT)
2357 				return (SSL_ERROR_WANT_ACCEPT);
2358 			else
2359 				return (SSL_ERROR_SYSCALL); /* unknown */
2360 		}
2361 	}
2362 
2363 	if ((i < 0) && SSL_want_write(s)) {
2364 		bio = SSL_get_wbio(s);
2365 		if (BIO_should_write(bio)) {
2366 			return (SSL_ERROR_WANT_WRITE);
2367 		} else if (BIO_should_read(bio)) {
2368 			/*
2369 			 * See above (SSL_want_read(s) with
2370 			 * BIO_should_write(bio))
2371 			 */
2372 			return (SSL_ERROR_WANT_READ);
2373 		} else if (BIO_should_io_special(bio)) {
2374 			reason = BIO_get_retry_reason(bio);
2375 			if (reason == BIO_RR_CONNECT)
2376 				return (SSL_ERROR_WANT_CONNECT);
2377 			else if (reason == BIO_RR_ACCEPT)
2378 				return (SSL_ERROR_WANT_ACCEPT);
2379 			else
2380 				return (SSL_ERROR_SYSCALL);
2381 		}
2382 	}
2383 	if ((i < 0) && SSL_want_x509_lookup(s)) {
2384 		return (SSL_ERROR_WANT_X509_LOOKUP);
2385 	}
2386 
2387 	if (i == 0) {
2388 		if ((s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2389 		    (S3I(s)->warn_alert == SSL_AD_CLOSE_NOTIFY))
2390 		return (SSL_ERROR_ZERO_RETURN);
2391 	}
2392 	return (SSL_ERROR_SYSCALL);
2393 }
2394 
2395 int
2396 SSL_do_handshake(SSL *s)
2397 {
2398 	int	ret = 1;
2399 
2400 	if (s->internal->handshake_func == NULL) {
2401 		SSLerror(s, SSL_R_CONNECTION_TYPE_NOT_SET);
2402 		return (-1);
2403 	}
2404 
2405 	s->method->internal->ssl_renegotiate_check(s);
2406 
2407 	if (SSL_in_init(s) || SSL_in_before(s)) {
2408 		ret = s->internal->handshake_func(s);
2409 	}
2410 	return (ret);
2411 }
2412 
2413 /*
2414  * For the next 2 functions, SSL_clear() sets shutdown and so
2415  * one of these calls will reset it
2416  */
2417 void
2418 SSL_set_accept_state(SSL *s)
2419 {
2420 	s->server = 1;
2421 	s->internal->shutdown = 0;
2422 	S3I(s)->hs.state = SSL_ST_ACCEPT|SSL_ST_BEFORE;
2423 	s->internal->handshake_func = s->method->internal->ssl_accept;
2424 	ssl_clear_cipher_state(s);
2425 }
2426 
2427 void
2428 SSL_set_connect_state(SSL *s)
2429 {
2430 	s->server = 0;
2431 	s->internal->shutdown = 0;
2432 	S3I(s)->hs.state = SSL_ST_CONNECT|SSL_ST_BEFORE;
2433 	s->internal->handshake_func = s->method->internal->ssl_connect;
2434 	ssl_clear_cipher_state(s);
2435 }
2436 
2437 int
2438 ssl_undefined_function(SSL *s)
2439 {
2440 	SSLerror(s, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2441 	return (0);
2442 }
2443 
2444 int
2445 ssl_undefined_void_function(void)
2446 {
2447 	SSLerrorx(ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2448 	return (0);
2449 }
2450 
2451 int
2452 ssl_undefined_const_function(const SSL *s)
2453 {
2454 	SSLerror(s, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2455 	return (0);
2456 }
2457 
2458 const char *
2459 ssl_version_string(int ver)
2460 {
2461 	switch (ver) {
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 	case DTLS1_VERSION:
2471 		return (SSL_TXT_DTLS1);
2472 	case DTLS1_2_VERSION:
2473 		return (SSL_TXT_DTLS1_2);
2474 	default:
2475 		return ("unknown");
2476 	}
2477 }
2478 
2479 const char *
2480 SSL_get_version(const SSL *s)
2481 {
2482 	return ssl_version_string(s->version);
2483 }
2484 
2485 SSL *
2486 SSL_dup(SSL *s)
2487 {
2488 	STACK_OF(X509_NAME) *sk;
2489 	X509_NAME *xn;
2490 	SSL *ret;
2491 	int i;
2492 
2493 	if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
2494 		goto err;
2495 
2496 	ret->version = s->version;
2497 	ret->internal->type = s->internal->type;
2498 	ret->method = s->method;
2499 
2500 	if (s->session != NULL) {
2501 		if (!SSL_copy_session_id(ret, s))
2502 			goto err;
2503 	} else {
2504 		/*
2505 		 * No session has been established yet, so we have to expect
2506 		 * that s->cert or ret->cert will be changed later --
2507 		 * they should not both point to the same object,
2508 		 * and thus we can't use SSL_copy_session_id.
2509 		 */
2510 
2511 		ret->method->internal->ssl_free(ret);
2512 		ret->method = s->method;
2513 		ret->method->internal->ssl_new(ret);
2514 
2515 		ssl_cert_free(ret->cert);
2516 		if ((ret->cert = ssl_cert_dup(s->cert)) == NULL)
2517 			goto err;
2518 
2519 		if (!SSL_set_session_id_context(ret, s->sid_ctx,
2520 		    s->sid_ctx_length))
2521 			goto err;
2522 	}
2523 
2524 	ret->internal->options = s->internal->options;
2525 	ret->internal->mode = s->internal->mode;
2526 	SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
2527 	SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
2528 	ret->internal->msg_callback = s->internal->msg_callback;
2529 	ret->internal->msg_callback_arg = s->internal->msg_callback_arg;
2530 	SSL_set_verify(ret, SSL_get_verify_mode(s),
2531 	SSL_get_verify_callback(s));
2532 	SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
2533 	ret->internal->generate_session_id = s->internal->generate_session_id;
2534 
2535 	SSL_set_info_callback(ret, SSL_get_info_callback(s));
2536 
2537 	ret->internal->debug = s->internal->debug;
2538 
2539 	/* copy app data, a little dangerous perhaps */
2540 	if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL,
2541 	    &ret->internal->ex_data, &s->internal->ex_data))
2542 		goto err;
2543 
2544 	/* setup rbio, and wbio */
2545 	if (s->rbio != NULL) {
2546 		if (!BIO_dup_state(s->rbio,(char *)&ret->rbio))
2547 			goto err;
2548 	}
2549 	if (s->wbio != NULL) {
2550 		if (s->wbio != s->rbio) {
2551 			if (!BIO_dup_state(s->wbio,(char *)&ret->wbio))
2552 				goto err;
2553 		} else
2554 			ret->wbio = ret->rbio;
2555 	}
2556 	ret->internal->rwstate = s->internal->rwstate;
2557 	ret->internal->in_handshake = s->internal->in_handshake;
2558 	ret->internal->handshake_func = s->internal->handshake_func;
2559 	ret->server = s->server;
2560 	ret->internal->renegotiate = s->internal->renegotiate;
2561 	ret->internal->new_session = s->internal->new_session;
2562 	ret->internal->quiet_shutdown = s->internal->quiet_shutdown;
2563 	ret->internal->shutdown = s->internal->shutdown;
2564 	/* SSL_dup does not really work at any state, though */
2565 	S3I(ret)->hs.state = S3I(s)->hs.state;
2566 	ret->internal->rstate = s->internal->rstate;
2567 
2568 	/*
2569 	 * Would have to copy ret->init_buf, ret->init_msg, ret->init_num,
2570 	 * ret->init_off
2571 	 */
2572 	ret->internal->init_num = 0;
2573 
2574 	ret->internal->hit = s->internal->hit;
2575 
2576 	X509_VERIFY_PARAM_inherit(ret->param, s->param);
2577 
2578 	if (s->cipher_list != NULL) {
2579 		if ((ret->cipher_list =
2580 		    sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
2581 			goto err;
2582 	}
2583 	if (s->internal->cipher_list_tls13 != NULL) {
2584 		if ((ret->internal->cipher_list_tls13 =
2585 		    sk_SSL_CIPHER_dup(s->internal->cipher_list_tls13)) == NULL)
2586 			goto err;
2587 	}
2588 
2589 	/* Dup the client_CA list */
2590 	if (s->internal->client_CA != NULL) {
2591 		if ((sk = sk_X509_NAME_dup(s->internal->client_CA)) == NULL) goto err;
2592 			ret->internal->client_CA = sk;
2593 		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2594 			xn = sk_X509_NAME_value(sk, i);
2595 			if (sk_X509_NAME_set(sk, i,
2596 			    X509_NAME_dup(xn)) == NULL) {
2597 				X509_NAME_free(xn);
2598 				goto err;
2599 			}
2600 		}
2601 	}
2602 
2603 	return ret;
2604  err:
2605 	SSL_free(ret);
2606 	return NULL;
2607 }
2608 
2609 void
2610 ssl_clear_cipher_state(SSL *s)
2611 {
2612 	ssl_clear_cipher_read_state(s);
2613 	ssl_clear_cipher_write_state(s);
2614 }
2615 
2616 void
2617 ssl_clear_cipher_read_state(SSL *s)
2618 {
2619 	tls12_record_layer_clear_read_state(s->internal->rl);
2620 	tls12_record_layer_read_cipher_hash(s->internal->rl,
2621 	    &s->enc_read_ctx, &s->read_hash);
2622 }
2623 
2624 void
2625 ssl_clear_cipher_write_state(SSL *s)
2626 {
2627 	tls12_record_layer_clear_write_state(s->internal->rl);
2628 }
2629 
2630 /* Fix this function so that it takes an optional type parameter */
2631 X509 *
2632 SSL_get_certificate(const SSL *s)
2633 {
2634 	return (s->cert->key->x509);
2635 }
2636 
2637 /* Fix this function so that it takes an optional type parameter */
2638 EVP_PKEY *
2639 SSL_get_privatekey(const SSL *s)
2640 {
2641 	return (s->cert->key->privatekey);
2642 }
2643 
2644 const SSL_CIPHER *
2645 SSL_get_current_cipher(const SSL *s)
2646 {
2647 	if ((s->session != NULL) && (s->session->cipher != NULL))
2648 		return (s->session->cipher);
2649 	return (NULL);
2650 }
2651 const void *
2652 SSL_get_current_compression(SSL *s)
2653 {
2654 	return (NULL);
2655 }
2656 
2657 const void *
2658 SSL_get_current_expansion(SSL *s)
2659 {
2660 	return (NULL);
2661 }
2662 
2663 size_t
2664 SSL_get_client_random(const SSL *s, unsigned char *out, size_t max_out)
2665 {
2666 	size_t len = sizeof(s->s3->client_random);
2667 
2668 	if (out == NULL)
2669 		return len;
2670 
2671 	if (len > max_out)
2672 		len = max_out;
2673 
2674 	memcpy(out, s->s3->client_random, len);
2675 
2676 	return len;
2677 }
2678 
2679 size_t
2680 SSL_get_server_random(const SSL *s, unsigned char *out, size_t max_out)
2681 {
2682 	size_t len = sizeof(s->s3->server_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->server_random, len);
2691 
2692 	return len;
2693 }
2694 
2695 int
2696 ssl_init_wbio_buffer(SSL *s, int push)
2697 {
2698 	BIO	*bbio;
2699 
2700 	if (s->bbio == NULL) {
2701 		bbio = BIO_new(BIO_f_buffer());
2702 		if (bbio == NULL)
2703 			return (0);
2704 		s->bbio = bbio;
2705 	} else {
2706 		bbio = s->bbio;
2707 		if (s->bbio == s->wbio)
2708 			s->wbio = BIO_pop(s->wbio);
2709 	}
2710 	(void)BIO_reset(bbio);
2711 /*	if (!BIO_set_write_buffer_size(bbio,16*1024)) */
2712 	if (!BIO_set_read_buffer_size(bbio, 1)) {
2713 		SSLerror(s, ERR_R_BUF_LIB);
2714 		return (0);
2715 	}
2716 	if (push) {
2717 		if (s->wbio != bbio)
2718 			s->wbio = BIO_push(bbio, s->wbio);
2719 	} else {
2720 		if (s->wbio == bbio)
2721 			s->wbio = BIO_pop(bbio);
2722 	}
2723 	return (1);
2724 }
2725 
2726 void
2727 ssl_free_wbio_buffer(SSL *s)
2728 {
2729 	if (s == NULL)
2730 		return;
2731 
2732 	if (s->bbio == NULL)
2733 		return;
2734 
2735 	if (s->bbio == s->wbio) {
2736 		/* remove buffering */
2737 		s->wbio = BIO_pop(s->wbio);
2738 	}
2739 	BIO_free(s->bbio);
2740 	s->bbio = NULL;
2741 }
2742 
2743 void
2744 SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
2745 {
2746 	ctx->internal->quiet_shutdown = mode;
2747 }
2748 
2749 int
2750 SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
2751 {
2752 	return (ctx->internal->quiet_shutdown);
2753 }
2754 
2755 void
2756 SSL_set_quiet_shutdown(SSL *s, int mode)
2757 {
2758 	s->internal->quiet_shutdown = mode;
2759 }
2760 
2761 int
2762 SSL_get_quiet_shutdown(const SSL *s)
2763 {
2764 	return (s->internal->quiet_shutdown);
2765 }
2766 
2767 void
2768 SSL_set_shutdown(SSL *s, int mode)
2769 {
2770 	s->internal->shutdown = mode;
2771 }
2772 
2773 int
2774 SSL_get_shutdown(const SSL *s)
2775 {
2776 	return (s->internal->shutdown);
2777 }
2778 
2779 int
2780 SSL_version(const SSL *s)
2781 {
2782 	return (s->version);
2783 }
2784 
2785 SSL_CTX *
2786 SSL_get_SSL_CTX(const SSL *ssl)
2787 {
2788 	return (ssl->ctx);
2789 }
2790 
2791 SSL_CTX *
2792 SSL_set_SSL_CTX(SSL *ssl, SSL_CTX* ctx)
2793 {
2794 	CERT *new_cert;
2795 
2796 	if (ctx == NULL)
2797 		ctx = ssl->initial_ctx;
2798 	if (ssl->ctx == ctx)
2799 		return (ssl->ctx);
2800 
2801 	if ((new_cert = ssl_cert_dup(ctx->internal->cert)) == NULL)
2802 		return NULL;
2803 	ssl_cert_free(ssl->cert);
2804 	ssl->cert = new_cert;
2805 
2806 	SSL_CTX_up_ref(ctx);
2807 	SSL_CTX_free(ssl->ctx); /* decrement reference count */
2808 	ssl->ctx = ctx;
2809 
2810 	return (ssl->ctx);
2811 }
2812 
2813 int
2814 SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
2815 {
2816 	return (X509_STORE_set_default_paths(ctx->cert_store));
2817 }
2818 
2819 int
2820 SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
2821     const char *CApath)
2822 {
2823 	return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
2824 }
2825 
2826 int
2827 SSL_CTX_load_verify_mem(SSL_CTX *ctx, void *buf, int len)
2828 {
2829 	return (X509_STORE_load_mem(ctx->cert_store, buf, len));
2830 }
2831 
2832 void
2833 SSL_set_info_callback(SSL *ssl, void (*cb)(const SSL *ssl, int type, int val))
2834 {
2835 	ssl->internal->info_callback = cb;
2836 }
2837 
2838 void (*SSL_get_info_callback(const SSL *ssl))(const SSL *ssl, int type, int val)
2839 {
2840 	return (ssl->internal->info_callback);
2841 }
2842 
2843 int
2844 SSL_state(const SSL *ssl)
2845 {
2846 	return (S3I(ssl)->hs.state);
2847 }
2848 
2849 void
2850 SSL_set_state(SSL *ssl, int state)
2851 {
2852 	S3I(ssl)->hs.state = state;
2853 }
2854 
2855 void
2856 SSL_set_verify_result(SSL *ssl, long arg)
2857 {
2858 	ssl->verify_result = arg;
2859 }
2860 
2861 long
2862 SSL_get_verify_result(const SSL *ssl)
2863 {
2864 	return (ssl->verify_result);
2865 }
2866 
2867 int
2868 SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2869     CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
2870 {
2871 	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp,
2872 	    new_func, dup_func, free_func));
2873 }
2874 
2875 int
2876 SSL_set_ex_data(SSL *s, int idx, void *arg)
2877 {
2878 	return (CRYPTO_set_ex_data(&s->internal->ex_data, idx, arg));
2879 }
2880 
2881 void *
2882 SSL_get_ex_data(const SSL *s, int idx)
2883 {
2884 	return (CRYPTO_get_ex_data(&s->internal->ex_data, idx));
2885 }
2886 
2887 int
2888 SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2889     CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
2890 {
2891 	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp,
2892 	    new_func, dup_func, free_func));
2893 }
2894 
2895 int
2896 SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
2897 {
2898 	return (CRYPTO_set_ex_data(&s->internal->ex_data, idx, arg));
2899 }
2900 
2901 void *
2902 SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
2903 {
2904 	return (CRYPTO_get_ex_data(&s->internal->ex_data, idx));
2905 }
2906 
2907 int
2908 ssl_ok(SSL *s)
2909 {
2910 	return (1);
2911 }
2912 
2913 X509_STORE *
2914 SSL_CTX_get_cert_store(const SSL_CTX *ctx)
2915 {
2916 	return (ctx->cert_store);
2917 }
2918 
2919 void
2920 SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
2921 {
2922 	X509_STORE_free(ctx->cert_store);
2923 	ctx->cert_store = store;
2924 }
2925 
2926 X509 *
2927 SSL_CTX_get0_certificate(const SSL_CTX *ctx)
2928 {
2929 	if (ctx->internal->cert == NULL)
2930 		return NULL;
2931 
2932 	return ctx->internal->cert->key->x509;
2933 }
2934 
2935 int
2936 SSL_want(const SSL *s)
2937 {
2938 	return (s->internal->rwstate);
2939 }
2940 
2941 void
2942 SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*cb)(SSL *ssl, int is_export,
2943     int keylength))
2944 {
2945 	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
2946 }
2947 
2948 void
2949 SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb)(SSL *ssl, int is_export,
2950     int keylength))
2951 {
2952 	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
2953 }
2954 
2955 void
2956 SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx, DH *(*dh)(SSL *ssl, int is_export,
2957     int keylength))
2958 {
2959 	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
2960 }
2961 
2962 void
2963 SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh)(SSL *ssl, int is_export,
2964     int keylength))
2965 {
2966 	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
2967 }
2968 
2969 void
2970 SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx, EC_KEY *(*ecdh)(SSL *ssl,
2971     int is_export, int keylength))
2972 {
2973 	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH_CB,
2974 	    (void (*)(void))ecdh);
2975 }
2976 
2977 void
2978 SSL_set_tmp_ecdh_callback(SSL *ssl, EC_KEY *(*ecdh)(SSL *ssl, int is_export,
2979     int keylength))
2980 {
2981 	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH_CB,(void (*)(void))ecdh);
2982 }
2983 
2984 
2985 void
2986 SSL_CTX_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version,
2987     int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
2988 {
2989 	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK,
2990 	    (void (*)(void))cb);
2991 }
2992 
2993 void
2994 SSL_set_msg_callback(SSL *ssl, void (*cb)(int write_p, int version,
2995     int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
2996 {
2997 	SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
2998 }
2999 
3000 void
3001 SSL_set_debug(SSL *s, int debug)
3002 {
3003 	s->internal->debug = debug;
3004 }
3005 
3006 int
3007 SSL_cache_hit(SSL *s)
3008 {
3009 	return (s->internal->hit);
3010 }
3011 
3012 int
3013 SSL_CTX_get_min_proto_version(SSL_CTX *ctx)
3014 {
3015 	return ctx->internal->min_proto_version;
3016 }
3017 
3018 int
3019 SSL_CTX_set_min_proto_version(SSL_CTX *ctx, uint16_t version)
3020 {
3021 	return ssl_version_set_min(ctx->method, version,
3022 	    ctx->internal->max_tls_version, &ctx->internal->min_tls_version,
3023 	    &ctx->internal->min_proto_version);
3024 }
3025 
3026 int
3027 SSL_CTX_get_max_proto_version(SSL_CTX *ctx)
3028 {
3029 	return ctx->internal->max_proto_version;
3030 }
3031 
3032 int
3033 SSL_CTX_set_max_proto_version(SSL_CTX *ctx, uint16_t version)
3034 {
3035 	return ssl_version_set_max(ctx->method, version,
3036 	    ctx->internal->min_tls_version, &ctx->internal->max_tls_version,
3037 	    &ctx->internal->max_proto_version);
3038 }
3039 
3040 int
3041 SSL_get_min_proto_version(SSL *ssl)
3042 {
3043 	return ssl->internal->min_proto_version;
3044 }
3045 
3046 int
3047 SSL_set_min_proto_version(SSL *ssl, uint16_t version)
3048 {
3049 	return ssl_version_set_min(ssl->method, version,
3050 	    ssl->internal->max_tls_version, &ssl->internal->min_tls_version,
3051 	    &ssl->internal->min_proto_version);
3052 }
3053 int
3054 SSL_get_max_proto_version(SSL *ssl)
3055 {
3056 	return ssl->internal->max_proto_version;
3057 }
3058 
3059 int
3060 SSL_set_max_proto_version(SSL *ssl, uint16_t version)
3061 {
3062 	return ssl_version_set_max(ssl->method, version,
3063 	    ssl->internal->min_tls_version, &ssl->internal->max_tls_version,
3064 	    &ssl->internal->max_proto_version);
3065 }
3066 
3067 static int
3068 ssl_cipher_id_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_)
3069 {
3070 	SSL_CIPHER const *a = a_;
3071 	SSL_CIPHER const *b = b_;
3072 	return ssl_cipher_id_cmp(a, b);
3073 }
3074 
3075 SSL_CIPHER *
3076 OBJ_bsearch_ssl_cipher_id(SSL_CIPHER *key, SSL_CIPHER const *base, int num)
3077 {
3078 	return (SSL_CIPHER *)OBJ_bsearch_(key, base, num, sizeof(SSL_CIPHER),
3079 	    ssl_cipher_id_cmp_BSEARCH_CMP_FN);
3080 }
3081