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