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